diff --git a/src/fathom/adapters/llm/gemini.py b/src/fathom/adapters/llm/gemini.py index b5ae7cb3..8e02fba0 100644 --- a/src/fathom/adapters/llm/gemini.py +++ b/src/fathom/adapters/llm/gemini.py @@ -11,6 +11,7 @@ from google.oauth2 import service_account from fathom.adapters.llm.cache import CacheService +from fathom.adapters.tools import GeminiToolDialect from fathom.constants.llm import ( GEMINI_CANCELLED_ERROR_MARKERS, GEMINI_CANCELLED_STATUS_CODE, @@ -33,17 +34,21 @@ GEMINI_VERTEX_REQUEST_TYPE_HEADER, GEMINI_VERTEX_SHARED_REQUEST_TYPE, InferenceTier, + ModelProvider, StructuredOutputMediaType, ) from fathom.core.exceptions import VisionError from fathom.core.inference.priority import PriorityInferencePolicy from fathom.core.services.parsing import ToolResponseParser from fathom.interfaces.llm import LLMPort +from fathom.interfaces.tools import CanonicalToolPayload from fathom.schemas.configuration import LLMConfiguration from fathom.schemas.conversation import ConversationTurn from fathom.schemas.llm import ( GeminiExceptionKind, GeminiExceptionMetadata, + InferenceSettings, + ModelIdentity, PriorityInferenceSignal, PriorityInferenceTransition, StructuredOutput, @@ -74,6 +79,8 @@ def __init__( else: self.__configuration = LLMConfiguration(api_key=api_key, model=model, use_cache=True) + self.__tool_dialect = GeminiToolDialect() + self.__client: Optional[Any] = None self.__credentials: Optional[Any] = None self.__priority = PriorityInferencePolicy(configuration=self.__configuration.priority) @@ -91,6 +98,22 @@ def model_name(self) -> str: return self.__configuration.model + @property + def identity(self) -> ModelIdentity: + """ + Declare the configured provider, model, and the settings that affect comparability. + """ + + return ModelIdentity( + provider=ModelProvider.declared(value=self.__configuration.provider), + model=self.__configuration.model, + settings=InferenceSettings( + cache=self.__configuration.use_cache, + thinking=self.__configuration.thinking_level, + temperature=self.__configuration.temperature, + ), + ) + def derive(self, *, overrides: LLMConfiguration) -> LLMPort: """ Spawn a sibling adapter sharing credentials and model, applying only the @@ -348,10 +371,12 @@ async def generate( if structured_output is not None and tools: raise VisionError("Structured-output mode cannot be combined with tool calling") + provider_tools = self.__encode_tools(tools=tools) + if use_cache and self.__cache and system_instruction and structured_output is None: cache_name = await self.__cache.get_cached_content( system_instruction=system_instruction, - tools=tools.get("function_declarations") if tools else None, + tools=provider_tools.get("function_declarations") if provider_tools else None, ) else: cache_name = None @@ -386,7 +411,7 @@ async def generate( config = self.__get_generation_configuration( tier=tier, - tools=tools, + tools=provider_tools, cache_name=active_cache_name, structured_output=structured_output, system_instruction=system_instruction, @@ -650,13 +675,28 @@ async def prewarm( if not self.__configuration.use_cache: return - declarations = tools.get("function_declarations") if tools is not None else None + provider_tools = self.__encode_tools(tools=tools) + declarations = provider_tools.get("function_declarations") if provider_tools else None await self.__cache.get_cached_content( tools=declarations, system_instruction=system_instruction, ) + def __encode_tools(self, *, tools: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: + """ + Translate canonical declarations at the Gemini adapter boundary. + + Accepting the legacy envelope keeps older integrations working while all migrated runtime + callers use the provider-neutral ``{"tools": [...]}`` shape. + """ + + if tools is None or "function_declarations" in tools: + return tools + + canonical: CanonicalToolPayload = {"tools": tools.get("tools", [])} + return self.__tool_dialect.encode(payload=canonical) + async def cleanup(self) -> None: """ Delete the provider cache, then close the SDK client. diff --git a/src/fathom/adapters/summarization/llm.py b/src/fathom/adapters/summarization/llm.py index e1cf8461..c5172312 100644 --- a/src/fathom/adapters/summarization/llm.py +++ b/src/fathom/adapters/summarization/llm.py @@ -25,6 +25,14 @@ def __init__(self, llm: LLMPort) -> None: self.__llm = llm + @property + def llm(self) -> LLMPort: + """ + The LLM adapter this summarizer was composed with. + """ + + return self.__llm + async def summarize_trace(self, trace: List[Dict[str, Any]]) -> str: """ Build a milestone summary of the trace via tool calling: the accomplishment, the key actions, @@ -77,7 +85,7 @@ async def summarize_trace(self, trace: List[Dict[str, Any]]) -> str: # Use tool calling for structured summarization tool_definition = { - "function_declarations": [ + "tools": [ { "name": "create_milestone", "description": "Create a structured milestone summary of the execution segment", diff --git a/src/fathom/adapters/tools/__init__.py b/src/fathom/adapters/tools/__init__.py new file mode 100644 index 00000000..0bae1209 --- /dev/null +++ b/src/fathom/adapters/tools/__init__.py @@ -0,0 +1,5 @@ +"""Expose provider tool-dialect adapters.""" + +from fathom.adapters.tools.gemini import GeminiToolDialect + +__all__ = ["GeminiToolDialect"] diff --git a/src/fathom/adapters/tools/gemini.py b/src/fathom/adapters/tools/gemini.py new file mode 100644 index 00000000..0b5e285e --- /dev/null +++ b/src/fathom/adapters/tools/gemini.py @@ -0,0 +1,20 @@ +"""Encode provider-neutral tools for the Gemini SDK.""" + +from __future__ import annotations + +from typing import Any, Dict, List, Mapping + +from fathom.interfaces.tools import ToolDeclaration, ToolDialect + + +class GeminiToolDialect(ToolDialect): + """ + Encode the provider-neutral tool contract as Gemini function declarations. + """ + + def encode(self, *, payload: Mapping[str, List[ToolDeclaration]]) -> Dict[str, Any]: + """ + Return the Gemini SDK envelope without mutating the canonical declarations. + """ + + return {"function_declarations": list(payload.get("tools", []))} diff --git a/src/fathom/constants/llm.py b/src/fathom/constants/llm.py index aa815e05..fa761369 100644 --- a/src/fathom/constants/llm.py +++ b/src/fathom/constants/llm.py @@ -96,3 +96,29 @@ class StructuredOutputMediaType(StrEnum): "invalid_argument", "invalid resource state", ) + + +class ModelProvider(StrEnum): + """ + Provider identity an LLM adapter declares for itself, never inferred from its class name. + + Values mirror the ``LLMConfiguration.provider`` vocabulary and are persisted on recorded + runs, so they keep that literal protocol form rather than the internal upper-case style. + """ + + GEMINI = "gemini" + VERTEX_AI = "vertex_ai" + OPENAI = "openai" + ANTHROPIC = "anthropic" + UNKNOWN = "unknown" + + @classmethod + def declared(cls, *, value: str) -> "ModelProvider": + """ + Map a configuration-declared provider value onto its typed identity. + """ + + try: + return cls(value) + except ValueError: + return cls.UNKNOWN diff --git a/src/fathom/constants/manifest.py b/src/fathom/constants/manifest.py new file mode 100644 index 00000000..a6530782 --- /dev/null +++ b/src/fathom/constants/manifest.py @@ -0,0 +1,53 @@ +"""Define model-role manifest constants and enums.""" + +from __future__ import annotations + +from enum import StrEnum +from typing import Final + +MANIFEST_VERSION: Final[int] = 1 + + +class ModelRole(StrEnum): + """ + A model-consuming role Fathom composes for a run. + """ + + PLANNER = "PLANNER" + ARCHITECT = "ARCHITECT" + QUALIFIER = "QUALIFIER" + SUMMARIZER = "SUMMARIZER" + ABORT = "ABORT" + LOCALIZER = "LOCALIZER" + EMBEDDER = "EMBEDDER" + ORACLE = "ORACLE" + + +class RoleBinding(StrEnum): + """ + How a role obtained its adapter relative to the other roles in the run. + """ + + INDEPENDENT = "INDEPENDENT" + DERIVED = "DERIVED" + SHARED = "SHARED" + NONE = "NONE" + UNKNOWN = "UNKNOWN" + + +SHARED_ARCHITECT_NOTE: Final[str] = ( + "derive() returned the planner adapter itself, so the architect is not a deterministic " + "sibling and runs at the planner's temperature and cache setting." +) +SHARED_QUALIFIER_NOTE: Final[str] = ( + "Qualifier runs on the planner adapter, so its inference configuration does not apply; a " + "dedicated adapter is built only when the runner is composed with an assembly." +) +UNDECLARED_BINDING_NOTE: Final[str] = ( + "Port does not expose the adapter it was composed with, so its relationship to the planner " + "is not determinable." +) +UNREAD_CONFIGURATION_NOTE: Final[str] = ( + "Composition ignores this role's configured model and enabled flag; the role runs on the " + "planner adapter." +) diff --git a/src/fathom/core/embedding/capability.py b/src/fathom/core/embedding/capability.py new file mode 100644 index 00000000..032f66b6 --- /dev/null +++ b/src/fathom/core/embedding/capability.py @@ -0,0 +1,20 @@ +"""Detect whether an LLM adapter supports embeddings.""" + +from __future__ import annotations + +from fathom.interfaces.embedding import EmbeddingCapable +from fathom.interfaces.llm import LLMPort + + +class EmbeddingCapability: + """ + Single rule for whether an LLM adapter can back a sibling embedding adapter. + """ + + @staticmethod + def available(*, llm: LLMPort) -> bool: + """ + Whether the adapter declares an embedding-capable client and has initialized one. + """ + + return isinstance(llm, EmbeddingCapable) and llm.client is not None diff --git a/src/fathom/core/services/qualifier/llm.py b/src/fathom/core/services/qualifier/llm.py index d63c5cfc..850b11de 100644 --- a/src/fathom/core/services/qualifier/llm.py +++ b/src/fathom/core/services/qualifier/llm.py @@ -43,6 +43,14 @@ def __init__( self.__prompt_builder = prompt_builder or GeminiQualifierPromptBuilder() self.__structured_output = StructuredOutput(payload=QualificationVerdict) + @property + def llm(self) -> LLMPort: + """ + The LLM adapter this qualifier was composed with. + """ + + return self.__llm + async def qualify(self, *, intent: str) -> QualificationVerdict: """ Classify the intent's executability and return a verdict. diff --git a/src/fathom/interfaces/embedding.py b/src/fathom/interfaces/embedding.py index 3f2e1d57..53a15852 100644 --- a/src/fathom/interfaces/embedding.py +++ b/src/fathom/interfaces/embedding.py @@ -1,11 +1,26 @@ from __future__ import annotations from abc import ABC, abstractmethod -from typing import Tuple +from typing import Any, Protocol, Tuple, runtime_checkable from fathom.schemas.embedding import EmbeddingResult +@runtime_checkable +class EmbeddingCapable(Protocol): + """ + Capability for an LLM adapter that exposes a client a sibling embedding adapter can share. + """ + + @property + def client(self) -> Any: + """ + Provider client reused for embedding calls; None until the adapter has initialized one. + """ + + ... + + class EmbeddingPort(ABC): """ Domain-facing port for producing dense embedding vectors over text. diff --git a/src/fathom/interfaces/llm.py b/src/fathom/interfaces/llm.py index 71a991c2..3630cf12 100644 --- a/src/fathom/interfaces/llm.py +++ b/src/fathom/interfaces/llm.py @@ -1,10 +1,20 @@ from __future__ import annotations from abc import ABC, abstractmethod -from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, Union - +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Optional, + Protocol, + Sequence, + Union, + runtime_checkable, +) + +from fathom.constants.llm import ModelProvider from fathom.schemas.conversation import ConversationTurn -from fathom.schemas.llm import StructuredOutput +from fathom.schemas.llm import ModelIdentity, StructuredOutput from fathom.schemas.results import GenerateResult if TYPE_CHECKING: @@ -14,6 +24,24 @@ PromptPart = Union[str, bytes, Dict[str, str]] +@runtime_checkable +class ModelBound(Protocol): + """ + Capability for a port that runs on a language model and exposes the adapter it was given. + + Lets the composition root tell whether two roles share one adapter or hold distinct ones, + which a comparison of their reported identities cannot decide. + """ + + @property + def llm(self) -> "LLMPort": + """ + The adapter this port was composed with. + """ + + ... + + class LLMPort(ABC): """ Provider-neutral port for language-model generation. @@ -28,6 +56,17 @@ def model_name(self) -> str: raise NotImplementedError + @property + def identity(self) -> ModelIdentity: + """ + Provider, model, and settings this adapter declares for itself. + + Default declares UNKNOWN: an adapter that does not state its provider is reported as + undeclared rather than guessed from its class name. + """ + + return ModelIdentity(provider=ModelProvider.UNKNOWN, model=self.model_name) + @abstractmethod async def generate( self, @@ -69,12 +108,14 @@ def derive(self, *, overrides: "LLMConfiguration") -> "LLMPort": Spawn a sibling adapter sharing credentials and model, with only the explicitly-set fields of ``overrides`` applied on top. - Default returns self; providers that support reconfiguration (e.g. Gemini) override - this to build a genuinely independent sibling. + Every provider adapter must implement this operation. Returning the planner itself would + silently discard role-specific settings such as deterministic temperature and caching. """ _ = overrides - return self + raise NotImplementedError( + f"{type(self).__name__} does not implement provider adapter derivation" + ) @abstractmethod async def cleanup(self) -> None: diff --git a/src/fathom/interfaces/tools.py b/src/fathom/interfaces/tools.py new file mode 100644 index 00000000..6ca8b282 --- /dev/null +++ b/src/fathom/interfaces/tools.py @@ -0,0 +1,26 @@ +"""Define provider-neutral tool declaration contracts.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import Any, Dict, List, Mapping + +ToolDeclaration = Dict[str, Any] +CanonicalToolPayload = Dict[str, List[ToolDeclaration]] + + +class ToolDialect(ABC): + """ + Translate Fathom's canonical tool contract into one provider's wire format. + + The canonical payload deliberately contains only the tool declarations. Provider-specific + envelope keys such as Gemini's ``function_declarations`` do not cross the LLM port boundary. + """ + + @abstractmethod + def encode(self, *, payload: Mapping[str, List[ToolDeclaration]]) -> Dict[str, Any]: + """ + Encode canonical declarations for the provider SDK. + """ + + raise NotImplementedError diff --git a/src/fathom/runtime/builder.py b/src/fathom/runtime/builder.py index 70682086..d88ed9c6 100644 --- a/src/fathom/runtime/builder.py +++ b/src/fathom/runtime/builder.py @@ -1,5 +1,6 @@ from __future__ import annotations +from logging import getLogger from typing import TYPE_CHECKING, List, Optional, cast from fathom.adapters.knowledge.sqlite import SQLiteKnowledge @@ -44,6 +45,9 @@ from fathom.runtime.runner import FathomRunner +logger = getLogger(__name__) + + class FathomBuilder: """ Fluent builder for Fathom configuration. @@ -333,8 +337,25 @@ def build(self) -> FathomRunner: self.__realignment = RealignmentPolicy() # Deterministic sibling of the planner for decomposition; runner owns its cleanup. - architect = self.__llm.derive(overrides=LLMConfiguration(temperature=0.0, use_cache=False)) - owned_resources.append(architect) + # An adapter that has not implemented derivation is shared explicitly, so the manifest + # can report the limitation instead of silently pretending it received the overrides. + try: + architect = self.__llm.derive( + overrides=LLMConfiguration(temperature=0.0, use_cache=False) + ) + except NotImplementedError: + architect = self.__llm + logger.warning( + "LLM adapter does not support derived role configuration; sharing planner", + extra={ + "component": "runtime.builder", + "event": "llm.role.derive.unavailable", + "role": "architect", + }, + ) + + if architect is not self.__llm: + owned_resources.append(architect) return FathomRunner( llm=self.__llm, diff --git a/src/fathom/runtime/manifest.py b/src/fathom/runtime/manifest.py new file mode 100644 index 00000000..65679127 --- /dev/null +++ b/src/fathom/runtime/manifest.py @@ -0,0 +1,272 @@ +"""Build the resolved model-role manifest for a run.""" + +from __future__ import annotations + +from typing import Any, List, Optional + +from fathom.constants.manifest import ( + SHARED_ARCHITECT_NOTE, + SHARED_QUALIFIER_NOTE, + UNDECLARED_BINDING_NOTE, + UNREAD_CONFIGURATION_NOTE, + ModelRole, + RoleBinding, +) +from fathom.core.embedding.capability import EmbeddingCapability +from fathom.interfaces.llm import LLMPort, ModelBound +from fathom.interfaces.qualifier import IntentQualifierPort +from fathom.interfaces.summarization import SummarizationPort +from fathom.schemas.abort import AbortDetectorConfiguration +from fathom.schemas.configuration import FathomConfiguration +from fathom.schemas.llm import ModelIdentity +from fathom.schemas.localization import EnsembleMemberName +from fathom.schemas.manifest import RequestedModel, RoleResolution, RuntimeManifest +from fathom.schemas.perception import LocalizationEnsembleConfiguration + + +class ManifestResolver: + """ + Projects the ports a runner was composed with into the resolved model-role manifest. + + Every role is read from the adapter instance that will serve it, so a role whose configured + model composition never honors is reported the way it runs rather than the way it was asked for. + """ + + def __init__( + self, + *, + planner: LLMPort, + architect: LLMPort, + qualifier: IntentQualifierPort, + summarizer: SummarizationPort, + configuration: FathomConfiguration, + ) -> None: + """ + Bind the composed ports and the configuration the run will execute under. + """ + + self.__planner = planner + self.__architect = architect + self.__qualifier = qualifier + self.__summarizer = summarizer + self.__configuration = configuration + + def resolve( + self, + *, + steps: int, + localization: LocalizationEnsembleConfiguration, + ) -> RuntimeManifest: + """ + Resolve every model-consuming role against the composed ports and the run's step budget. + """ + + planner = self.__identity(llm=self.__planner) + + roles: List[RoleResolution] = [ + self.__planner_role(planner=planner), + self.__architect_role(planner=planner), + self.__qualifier_role(), + self.__summarizer_role(), + self.__abort_role(planner=planner), + self.__localizer_role(planner=planner, localization=localization), + self.__embedder_role(planner=planner), + self.__oracle_role(planner=planner), + ] + + return RuntimeManifest(steps=steps, roles=tuple(roles)) + + @staticmethod + def __planner_role(*, planner: Optional[ModelIdentity]) -> RoleResolution: + """ + The planner owns its adapter; the caller injects the port rather than requesting a model. + """ + + return RoleResolution( + role=ModelRole.PLANNER, + enabled=True, + binding=RoleBinding.INDEPENDENT, + resolved=planner, + ) + + def __architect_role(self, *, planner: Optional[ModelIdentity]) -> RoleResolution: + """ + The architect is a derived sibling only when ``derive()`` returned a distinct adapter. + """ + + distinct = self.__architect is not self.__planner + + return RoleResolution( + role=ModelRole.ARCHITECT, + enabled=True, + source=ModelRole.PLANNER, + binding=RoleBinding.DERIVED if distinct else RoleBinding.SHARED, + resolved=self.__identity(llm=self.__architect), + note=None if distinct else SHARED_ARCHITECT_NOTE, + requested=None if planner is None else RequestedModel(model=planner.model), + ) + + def __qualifier_role(self) -> RoleResolution: + """ + The qualifier is independent only when composition built it a dedicated adapter. + """ + + configuration = self.__configuration.qualifier + requested = RequestedModel(model=configuration.inference.model) + + if not configuration.enabled: + return RoleResolution( + role=ModelRole.QUALIFIER, + enabled=False, + binding=RoleBinding.NONE, + requested=requested, + ) + + return self.__bound_role( + role=ModelRole.QUALIFIER, + port=self.__qualifier, + requested=requested, + shared_note=SHARED_QUALIFIER_NOTE, + ) + + def __summarizer_role(self) -> RoleResolution: + """ + The summarizer reuses the planner adapter unless the caller supplied its own port. + """ + + return self.__bound_role(role=ModelRole.SUMMARIZER, port=self.__summarizer) + + def __abort_role(self, *, planner: Optional[ModelIdentity]) -> RoleResolution: + """ + The abort detector always runs, always on the planner adapter, whatever it configures. + """ + + configuration = AbortDetectorConfiguration() + + return RoleResolution( + role=ModelRole.ABORT, + enabled=True, + resolved=planner, + source=ModelRole.PLANNER, + binding=RoleBinding.SHARED, + note=UNREAD_CONFIGURATION_NOTE, + requested=RequestedModel(model=configuration.inference.model), + ) + + def __localizer_role( + self, + *, + planner: Optional[ModelIdentity], + localization: LocalizationEnsembleConfiguration, + ) -> RoleResolution: + """ + The vision localizer runs on the planner adapter when its ensemble member is configured. + """ + + enabled = localization.enabled and any( + member in (EnsembleMemberName.VISION_LLM, EnsembleMemberName.GEMINI_VISION) + for member in localization.members + ) + + return self.__shared_role(role=ModelRole.LOCALIZER, enabled=enabled, planner=planner) + + def __embedder_role(self, *, planner: Optional[ModelIdentity]) -> RoleResolution: + """ + The embedder exists only when the planner adapter exposes a client it can share. + """ + + enabled = EmbeddingCapability.available(llm=self.__planner) + + return self.__shared_role(role=ModelRole.EMBEDDER, enabled=enabled, planner=planner) + + def __oracle_role(self, *, planner: Optional[ModelIdentity]) -> RoleResolution: + """ + The shadow criterion oracle runs on the planner adapter when configuration enables it. + """ + + enabled = self.__configuration.oracle.enabled + + return self.__shared_role(role=ModelRole.ORACLE, enabled=enabled, planner=planner) + + def __bound_role( + self, + *, + role: ModelRole, + port: Any, + requested: Optional[RequestedModel] = None, + shared_note: Optional[str] = None, + ) -> RoleResolution: + """ + Build a role whose adapter is read from the port itself, comparing it against the planner. + + A port that does not expose its adapter is reported as undeclared rather than assumed to + be independent, because assuming independence would hide a shared planner adapter. + """ + + adapter = self.__adapter(port=port) + + if adapter is None: + return RoleResolution( + role=role, + enabled=True, + requested=requested, + binding=RoleBinding.UNKNOWN, + note=UNDECLARED_BINDING_NOTE, + ) + + shared = adapter is self.__planner + + return RoleResolution( + role=role, + enabled=True, + requested=requested, + resolved=self.__identity(llm=adapter), + binding=RoleBinding.SHARED if shared else RoleBinding.INDEPENDENT, + source=ModelRole.PLANNER if shared else None, + note=shared_note if shared else None, + ) + + @staticmethod + def __shared_role( + *, + role: ModelRole, + enabled: bool, + planner: Optional[ModelIdentity], + ) -> RoleResolution: + """ + Build a role that has no adapter of its own and runs on the planner's when enabled. + """ + + return RoleResolution( + role=role, + enabled=enabled, + resolved=planner if enabled else None, + source=ModelRole.PLANNER if enabled else None, + binding=RoleBinding.SHARED if enabled else RoleBinding.NONE, + ) + + @staticmethod + def __adapter(*, port: Any) -> Optional[LLMPort]: + """ + Read the adapter a port was composed with, or None when the port does not expose one. + """ + + if not isinstance(port, ModelBound): + return None + + adapter = port.llm + + return adapter if isinstance(adapter, LLMPort) else None + + @staticmethod + def __identity(*, llm: LLMPort) -> Optional[ModelIdentity]: + """ + Read an adapter's declared identity, returning None when it declares nothing usable. + + Third-party adapters and test doubles reach this boundary, so one that answers with + something other than a :class:`ModelIdentity` is reported as undeclared, never guessed. + """ + + identity = llm.identity + + return identity if isinstance(identity, ModelIdentity) else None diff --git a/src/fathom/runtime/runner.py b/src/fathom/runtime/runner.py index c7ca34be..1bacbbcc 100644 --- a/src/fathom/runtime/runner.py +++ b/src/fathom/runtime/runner.py @@ -27,6 +27,7 @@ ArtifactBackend, TaskCode, ) +from fathom.constants.llm import ModelProvider from fathom.constants.qualification import DEFAULT_REJECTION_MESSAGE, RationaleCategory from fathom.constants.screen import ( MEMORY_SUMMARY_HASH_PREVIEW_LENGTH, @@ -61,9 +62,12 @@ from fathom.interfaces.summarization import SummarizationPort from fathom.interfaces.telemetry import TelemetryLevel, TelemetryPort from fathom.runtime.inspection import RuntimeConfigurationInspector +from fathom.runtime.manifest import ManifestResolver from fathom.schemas.configuration import FathomConfiguration from fathom.schemas.conversation import ActorInput from fathom.schemas.exploration import ExplorationGraph +from fathom.schemas.llm import ModelIdentity +from fathom.schemas.manifest import RuntimeManifest from fathom.schemas.qualification import QualificationVerdict from fathom.schemas.recording import Completion, Handle, Output, Run, ScriptOutput from fathom.schemas.results import ExplorationResult, IntentResult @@ -191,6 +195,15 @@ def __init__( message=self.__config.telemetry.phase, ) + self.__manifest_resolver = ManifestResolver( + planner=llm, + architect=self.__architect, + qualifier=qualifier, + summarizer=summarizer, + configuration=self.__config, + ) + self.__manifest: Optional[RuntimeManifest] = None + self.__catalog = CommandCatalogProvider().build() self.__capture_store = CaptureStore() self.__engine = ExecutionEngine( @@ -242,6 +255,10 @@ def __log_configuration_summary(self) -> None: "package": VersionInfo.payload(), "event": "fathom.runner.configured", "runtime_configuration_bound": self.__runtime_configuration is not None, + "effective_llm": { + "provider": self.__llm_provider(), + "model": self.__llm_model(), + }, }, ) @@ -292,6 +309,35 @@ def context(self) -> Optional[ContextManager]: return self.__context_manager + @property + def manifest(self) -> Optional[RuntimeManifest]: + """ + Model-role manifest resolved for the most recent run, or None before one starts. + """ + + return self.__manifest + + def __resolve_manifest(self, *, steps: int, loader: RuntimeConfigLoader) -> RuntimeManifest: + """ + Resolve and record the run's model-role manifest, then emit it as one structured event. + """ + + manifest = self.__manifest_resolver.resolve( + steps=steps, + localization=loader.localization(), + ) + self.__manifest = manifest + + logger.info( + "Fathom model roles resolved", + extra={ + "component": "runtime.runner", + "event": "fathom.manifest.resolved", + "manifest": manifest.model_dump(mode="json"), + }, + ) + return manifest + async def run_intent( self, *, @@ -299,7 +345,7 @@ async def run_intent( request_id: str, principal: Principal, max_steps: int = 50, - use_xml: bool = False, + use_xml: Optional[bool] = None, execution_id: Optional[str] = None, package_name: Optional[str] = None, realignment: Optional[RealignmentPolicy] = None, @@ -340,16 +386,24 @@ async def run_intent( self.__sync_telemetry_identity(workflow=workflow_id) + # Resolve the loader once so the manifest reports the same adapter mix the strategy + # composes, rather than a second env read that could disagree with it. + loader = self.__runtime_configuration or RuntimeConfigLoader() + steps = max_steps or self.__config.intent.max_steps + manifest = self.__resolve_manifest(steps=steps, loader=loader) + await self.__telemetry.info( "Starting intent workflow", intent=intent, max_steps=max_steps, workflow_id=workflow_id, context_scope=context_scope, + manifest=manifest.model_dump(mode="json"), ) rejection = await self.__qualify_or_reject( intent=intent, + manifest=manifest, start_time=start_time, workflow_id=workflow_id, ) @@ -442,9 +496,9 @@ async def run_intent( perception=self.__perception, path_manager=self.__path_manager, realignment=realignment or self.__realignment, - runtime_configuration=self.__runtime_configuration, + runtime_configuration=loader, plans=LangGraphPlanStore(), - max_steps=max_steps or self.__config.intent.max_steps, + max_steps=steps, use_xml=use_xml if use_xml is not None else self.__config.intent.use_xml_grounding, ) self.__current_strategy = strategy @@ -509,6 +563,7 @@ async def run_intent( error=error, status=status, intent=intent, + manifest=manifest, metrics=metrics, success=success, duration=duration, @@ -961,6 +1016,7 @@ async def __qualify_or_reject( intent: str, workflow_id: str, start_time: float, + manifest: RuntimeManifest, ) -> Optional[IntentResult]: """ Qualify the intent before any device interaction. @@ -1018,6 +1074,7 @@ async def __qualify_or_reject( return await self.__build_rejection_result( intent=intent, verdict=verdict, + manifest=manifest, start_time=start_time, workflow_id=workflow_id, verdict_payload=verdict_payload, @@ -1046,6 +1103,7 @@ async def __build_rejection_result( intent: str, workflow_id: str, start_time: float, + manifest: RuntimeManifest, verdict: QualificationVerdict, verdict_payload: Dict[str, Any], ) -> IntentResult: @@ -1081,6 +1139,7 @@ async def __build_rejection_result( error=None, metrics={}, intent=intent, + manifest=manifest, success=False, steps_taken=0, subgoal_count=0, @@ -1357,11 +1416,15 @@ def __task_code(self, *, success: bool, reason: str) -> TaskCode: def __llm_provider(self) -> str: """ - Derive a stable provider hint from the configured LLM adapter. + Return the provider the planner adapter declares for itself. """ - provider = self.__llm.__class__.__name__.removesuffix("LLM").lower() - return provider or "unknown" + identity = self.__llm.identity + + if not isinstance(identity, ModelIdentity): + return ModelProvider.UNKNOWN.value + + return identity.provider.value def __llm_model(self) -> Optional[str]: """ diff --git a/src/fathom/schemas/llm.py b/src/fathom/schemas/llm.py index 6f878ba5..d2ecc50a 100644 --- a/src/fathom/schemas/llm.py +++ b/src/fathom/schemas/llm.py @@ -5,10 +5,55 @@ from pydantic import BaseModel, ConfigDict, Field -from fathom.constants.llm import InferencePriorityTransitionReason, InferenceTier +from fathom.constants.llm import ( + InferencePriorityTransitionReason, + InferenceTier, + ModelProvider, +) from fathom.schemas.base.common import ThresholdConfiguration +class InferenceSettings(BaseModel): + """ + Non-secret inference settings that change a model's behavior between otherwise identical runs. + """ + + model_config = ConfigDict(frozen=True) + + cache: Optional[bool] = Field( + default=None, + description="Whether the adapter reuses provider-side prompt caching.", + ) + thinking: Optional[str] = Field( + default=None, + description="Reasoning-depth level the adapter requests, when the provider exposes one.", + ) + temperature: Optional[float] = Field( + default=None, + description="Sampling temperature the adapter is configured with.", + ) + + +class ModelIdentity(BaseModel): + """ + Provider and model an instantiated LLM adapter resolves to, as the adapter itself declares it. + """ + + model_config = ConfigDict(frozen=True) + + provider: ModelProvider = Field( + description="Provider the adapter declares; UNKNOWN when it declares none.", + ) + model: Optional[str] = Field( + default=None, + description="Model identifier the adapter is bound to.", + ) + settings: InferenceSettings = Field( + default_factory=InferenceSettings, + description="Fairness-relevant inference settings the adapter applies.", + ) + + class StructuredOutput(BaseModel): """ Vendor-neutral specification for constrained-decoding LLM output. diff --git a/src/fathom/schemas/localization.py b/src/fathom/schemas/localization.py index 6e53ae13..48445033 100644 --- a/src/fathom/schemas/localization.py +++ b/src/fathom/schemas/localization.py @@ -434,6 +434,10 @@ class EnsembleMemberName(StrEnum): Stable names for ensemble vision-localizer members. """ + VISION_LLM = "vision_llm" + """Provider-neutral LLM-backed visual localizer.""" + + # Retained so existing FATHOM_ENSEMBLE_LOCALIZER_MEMBERS values continue to parse. GEMINI_VISION = "gemini_vision" DOCUMENT_AI_LAYOUT = "document_ai_layout" diff --git a/src/fathom/schemas/manifest.py b/src/fathom/schemas/manifest.py new file mode 100644 index 00000000..fd8c6e7a --- /dev/null +++ b/src/fathom/schemas/manifest.py @@ -0,0 +1,98 @@ +"""Define immutable model-role manifest records.""" + +from __future__ import annotations + +from typing import Optional, Tuple + +from pydantic import BaseModel, ConfigDict, Field + +from fathom.constants.llm import ModelProvider +from fathom.constants.manifest import MANIFEST_VERSION, ModelRole, RoleBinding +from fathom.schemas.llm import ModelIdentity + + +class RequestedModel(BaseModel): + """ + Provider and model a role's configuration asked for, before composition resolved it. + """ + + model_config = ConfigDict(frozen=True) + + provider: Optional[ModelProvider] = Field( + default=None, + description="Provider the role's configuration declared, when it declares one.", + ) + model: Optional[str] = Field( + default=None, + description="Model identifier the role's configuration asked for.", + ) + + +class RoleResolution(BaseModel): + """ + How one model-consuming role resolved for a run. + """ + + model_config = ConfigDict(frozen=True) + + role: ModelRole = Field(description="The model-consuming role this entry describes.") + enabled: bool = Field(description="Whether the role runs at all for this run.") + binding: RoleBinding = Field( + description="Whether the role owns its adapter, derives one, shares another role's, or has none.", + ) + source: Optional[ModelRole] = Field( + default=None, + description="Role this one derives from or shares an adapter with.", + ) + requested: Optional[RequestedModel] = Field( + default=None, + description="What configuration asked for; absent when the role declares no model of its own.", + ) + resolved: Optional[ModelIdentity] = Field( + default=None, + description="What the instantiated adapter reports; absent when the role is disabled.", + ) + note: Optional[str] = Field( + default=None, + description="Why requested and resolved disagree, when composition ignores the request.", + ) + + +class RuntimeManifest(BaseModel): + """ + Every model-consuming role Fathom resolved for one run, with the step budget it runs under. + """ + + model_config = ConfigDict(frozen=True) + + version: int = Field( + default=MANIFEST_VERSION, + description="Manifest schema version, so a stored manifest outlives the code that wrote it.", + ) + steps: int = Field( + ge=0, + description="Effective maximum steps for the run, after request and configuration defaults resolve.", + ) + roles: Tuple[RoleResolution, ...] = Field( + description="One entry per model-consuming role, enabled or not.", + ) + + def entry(self, *, role: ModelRole) -> Optional[RoleResolution]: + """ + Return the resolution recorded for one role, or None when the role is absent. + """ + + return next((entry for entry in self.roles if entry.role == role), None) + + def providers(self) -> Tuple[ModelProvider, ...]: + """ + Return the distinct providers every enabled role resolved to, in role order. + """ + + seen: list[ModelProvider] = [] + + for entry in self.roles: + if entry.resolved is not None and entry.resolved.provider not in seen: + seen.append(entry.resolved.provider) + + return tuple(seen) diff --git a/src/fathom/schemas/results.py b/src/fathom/schemas/results.py index e6300de3..3e4b170f 100644 --- a/src/fathom/schemas/results.py +++ b/src/fathom/schemas/results.py @@ -13,6 +13,7 @@ from fathom.schemas.base.common import NonBlank from fathom.schemas.capture import Capture from fathom.schemas.delta import DeltaSignal +from fathom.schemas.manifest import RuntimeManifest from fathom.schemas.planner import PlannerEvent, PlannerMetrics from fathom.schemas.screens import ScreenCapture from fathom.schemas.shadow import ShadowTurnDraft @@ -212,6 +213,11 @@ class IntentResult(WorkflowResult): default=0, ge=0, description="Total number of sub-goals in the decomposition" ) + manifest: Optional[RuntimeManifest] = Field( + default=None, + description="Model roles resolved for this run; None for results produced before it existed.", + ) + class ExplorationResult(WorkflowResult): """ diff --git a/tests/unit/adapters/llm/test_gemini.py b/tests/unit/adapters/llm/test_gemini.py index b10f9b8a..9792d943 100644 --- a/tests/unit/adapters/llm/test_gemini.py +++ b/tests/unit/adapters/llm/test_gemini.py @@ -17,6 +17,7 @@ GEMINI_VERTEX_REQUEST_TYPE_HEADER, GEMINI_VERTEX_SHARED_REQUEST_TYPE, InferenceTier, + ModelProvider, ) from fathom.core.exceptions import VisionError from fathom.schemas.configuration import LLMConfiguration @@ -510,3 +511,96 @@ def test_collect_returns_empty_when_usage_absent(self) -> None: metrics = GeminiLLM._GeminiLLM__collect_usage_metrics(response=response) self.assertEqual(metrics, {}) + + +class GeminiIdentityTest(unittest.TestCase): + """ + The adapter declares its own provider and fairness-relevant settings rather than + leaving the runtime to infer them from its class name. + """ + + @staticmethod + def __gemini(*, configuration: LLMConfiguration) -> GeminiLLM: + """ + Bind a configuration without building an SDK client, which identity does not consult. + """ + + gemini = object.__new__(GeminiLLM) + gemini._GeminiLLM__configuration = configuration + return gemini + + def test_identity_reports_the_configured_provider_model_and_settings(self) -> None: + """ + A gemini-provider configuration surfaces as GEMINI with its temperature, cache, thinking. + """ + + gemini = self.__gemini( + configuration=LLMConfiguration( + model="gemini-3.5-flash", + temperature=0.25, + use_cache=False, + thinking_level="high", + ) + ) + + identity = gemini.identity + + self.assertEqual(identity.provider, ModelProvider.GEMINI) + self.assertEqual(identity.model, "gemini-3.5-flash") + self.assertEqual(identity.settings.temperature, 0.25) + self.assertEqual(identity.settings.thinking, "high") + self.assertFalse(identity.settings.cache) + + def test_vertex_configuration_reports_its_own_provider(self) -> None: + """ + The same adapter class configured for Vertex declares VERTEX_AI, not GEMINI. + """ + + gemini = self.__gemini( + configuration=LLMConfiguration(provider="vertex_ai", model="gemini-3.5-flash") + ) + + self.assertEqual(gemini.identity.provider, ModelProvider.VERTEX_AI) + + def test_derived_sibling_reports_the_overridden_settings(self) -> None: + """ + A sibling built by derive() declares the deterministic settings it was given. + """ + + planner = GeminiLLM( + configuration=LLMConfiguration( + api_key="test-key", model="gemini-3.5-flash", temperature=1.0, use_cache=True + ) + ) + + architect = planner.derive( + overrides=LLMConfiguration(temperature=0.0, use_cache=False), + ) + + self.assertIsNot(architect, planner) + self.assertEqual(planner.identity.settings.temperature, 1.0) + self.assertEqual(architect.identity.settings.temperature, 0.0) + self.assertEqual(architect.identity.model, planner.identity.model) + + +class ModelProviderDeclarationTest(unittest.TestCase): + """ + Provider identity comes from the declared configuration value, not from string guessing. + """ + + def test_every_configuration_provider_literal_maps_to_a_member(self) -> None: + """ + Each value LLMConfiguration.provider accepts resolves to a distinct typed provider. + """ + + self.assertEqual(ModelProvider.declared(value="gemini"), ModelProvider.GEMINI) + self.assertEqual(ModelProvider.declared(value="openai"), ModelProvider.OPENAI) + self.assertEqual(ModelProvider.declared(value="anthropic"), ModelProvider.ANTHROPIC) + self.assertEqual(ModelProvider.declared(value="vertex_ai"), ModelProvider.VERTEX_AI) + + def test_unrecognized_value_resolves_to_unknown(self) -> None: + """ + An unfamiliar provider string is reported as UNKNOWN rather than coerced or raised. + """ + + self.assertEqual(ModelProvider.declared(value="mystery"), ModelProvider.UNKNOWN) diff --git a/tests/unit/adapters/tools/test_gemini.py b/tests/unit/adapters/tools/test_gemini.py new file mode 100644 index 00000000..a6bf965c --- /dev/null +++ b/tests/unit/adapters/tools/test_gemini.py @@ -0,0 +1,34 @@ +"""Verify Gemini tool-dialect encoding and exports.""" + +from __future__ import annotations + +import unittest + +import fathom.adapters.tools as tools +from fathom.adapters.tools import GeminiToolDialect + + +class GeminiToolDialectTest(unittest.TestCase): + """ + Gemini tool translation remains self-contained in the provider-neutral foundation. + """ + + def test_foundation_exports_only_the_available_dialect(self) -> None: + """ + The foundation package must not import a dialect introduced by a child PR. + """ + + self.assertEqual(tools.__all__, ["GeminiToolDialect"]) + self.assertIs(tools.GeminiToolDialect, GeminiToolDialect) + + def test_encode_wraps_canonical_declarations_without_mutating_them(self) -> None: + """ + Gemini translation adds its SDK envelope and leaves the canonical declaration intact. + """ + + declaration = {"name": "execute_ui", "parameters": {"type": "object"}} + + encoded = GeminiToolDialect().encode(payload={"tools": [declaration]}) + + self.assertEqual(encoded, {"function_declarations": [declaration]}) + self.assertEqual(declaration, {"name": "execute_ui", "parameters": {"type": "object"}}) diff --git a/tests/unit/core/embedding/test_capability.py b/tests/unit/core/embedding/test_capability.py new file mode 100644 index 00000000..83b09413 --- /dev/null +++ b/tests/unit/core/embedding/test_capability.py @@ -0,0 +1,95 @@ +"""Verify embedding-capability detection across LLM adapters.""" + +from __future__ import annotations + +import unittest +from typing import Any, Dict, Optional, Sequence + +from fathom.core.embedding.capability import EmbeddingCapability +from fathom.interfaces.llm import LLMPort, PromptPart +from fathom.schemas.conversation import ConversationTurn +from fathom.schemas.llm import StructuredOutput +from fathom.schemas.results import GenerateResult + + +class _BareLLM(LLMPort): + """ + LLM double that exposes no client, as a non-Gemini adapter does. + """ + + @property + def model_name(self) -> str: + """ + Model identifier this double reports. + """ + + return "bare-1" + + async def generate( + self, + *, + use_cache: bool, + prompt: Sequence[PromptPart], + tools: Optional[Dict[str, Any]] = None, + system_instruction: Optional[str] = None, + conversation_history: Optional[Sequence[ConversationTurn]] = None, + structured_output: Optional[StructuredOutput] = None, + ) -> GenerateResult: + """ + Unused by the capability check. + """ + + raise NotImplementedError + + async def cleanup(self) -> None: + """ + Unused by the capability check. + """ + + +class _ClientLLM(_BareLLM): + """ + LLM double that exposes a client attribute, initialized or not. + """ + + def __init__(self, *, client: Optional[object]) -> None: + """ + Record the client this double exposes. + """ + + self.__client = client + + @property + def client(self) -> Optional[object]: + """ + Provider client a sibling embedding adapter would share. + """ + + return self.__client + + +class EmbeddingCapabilityTest(unittest.TestCase): + """ + The embedding capability is decided by the typed port contract, never by attribute probing. + """ + + def test_adapter_without_a_client_is_not_capable(self) -> None: + """ + An adapter that declares no client cannot back an embedding adapter. + """ + + self.assertFalse(EmbeddingCapability.available(llm=_BareLLM())) + + def test_adapter_with_an_initialized_client_is_capable(self) -> None: + """ + An adapter exposing a live client can back an embedding adapter. + """ + + self.assertTrue(EmbeddingCapability.available(llm=_ClientLLM(client=object()))) + + def test_adapter_whose_client_never_initialized_is_not_capable(self) -> None: + """ + Declaring the attribute is not enough; a None client means construction never completed. + """ + + self.assertFalse(EmbeddingCapability.available(llm=_ClientLLM(client=None))) diff --git a/tests/unit/interfaces/test_llm.py b/tests/unit/interfaces/test_llm.py new file mode 100644 index 00000000..15a0ae05 --- /dev/null +++ b/tests/unit/interfaces/test_llm.py @@ -0,0 +1,150 @@ +"""Verify the provider-neutral LLM interface contract.""" + +from __future__ import annotations + +import unittest +from typing import Any, Dict, Optional, Sequence + +from fathom.constants.llm import ModelProvider +from fathom.interfaces.llm import LLMPort, ModelBound, PromptPart +from fathom.schemas.configuration import LLMConfiguration +from fathom.schemas.conversation import ConversationTurn +from fathom.schemas.llm import ModelIdentity, StructuredOutput +from fathom.schemas.results import GenerateResult + + +class _LegacyLLM(LLMPort): + """ + LLM implementation written before the identity capability existed. + + Implements only the three members the port required then, so it stands in for every + third-party adapter already in the wild. + """ + + @property + def model_name(self) -> str: + """ + Model identifier this adapter reports. + """ + + return "legacy-1" + + async def generate( + self, + *, + use_cache: bool, + prompt: Sequence[PromptPart], + tools: Optional[Dict[str, Any]] = None, + system_instruction: Optional[str] = None, + conversation_history: Optional[Sequence[ConversationTurn]] = None, + structured_output: Optional[StructuredOutput] = None, + ) -> GenerateResult: + """ + Unused by these tests. + """ + + raise NotImplementedError + + async def cleanup(self) -> None: + """ + Unused by these tests. + """ + + +class LLMPortIdentityDefaultTest(unittest.TestCase): + """ + The identity capability is additive: adapters written against the previous port contract + still construct, and report an undeclared provider rather than a guessed one. + """ + + def test_adapter_predating_the_capability_still_instantiates(self) -> None: + """ + No new abstract member was added, so an existing implementation is still concrete. + """ + + self.assertEqual(_LegacyLLM().model_name, "legacy-1") + + def test_default_identity_declares_unknown_and_keeps_the_model_name(self) -> None: + """ + The default reports UNKNOWN with the adapter's own model, never a class-derived name. + """ + + identity = _LegacyLLM().identity + + self.assertEqual(identity.provider, ModelProvider.UNKNOWN) + self.assertEqual(identity.model, "legacy-1") + self.assertNotIn("legacy", identity.provider.value) + + def test_default_identity_declares_no_inference_settings(self) -> None: + """ + An adapter that states no settings reports them absent rather than as defaults. + """ + + settings = _LegacyLLM().identity.settings + + self.assertIsNone(settings.cache) + self.assertIsNone(settings.thinking) + self.assertIsNone(settings.temperature) + + def test_default_derive_requires_provider_implementation(self) -> None: + """ + A provider that cannot derive a role must fail explicitly instead of silently sharing + planner settings with the architect. + """ + + adapter = _LegacyLLM() + + with self.assertRaises(NotImplementedError): + adapter.derive(overrides=LLMConfiguration(temperature=0.0)) + + +class ModelBoundProtocolTest(unittest.TestCase): + """ + The ModelBound capability is structural, so a port satisfies it by exposing its adapter. + """ + + def test_port_without_an_llm_attribute_does_not_satisfy_the_capability(self) -> None: + """ + An LLM adapter is not itself a model-bound role port; it has no adapter to expose. + """ + + self.assertFalse(isinstance(_LegacyLLM(), ModelBound)) + + def test_port_exposing_its_adapter_satisfies_the_capability(self) -> None: + """ + Any object exposing an ``llm`` property is recognized without inheriting anything. + """ + + adapter = _LegacyLLM() + + class _Role: + """ + Minimal role port exposing the adapter it was composed with. + """ + + @property + def llm(self) -> LLMPort: + """ + The adapter this role was composed with. + """ + + return adapter + + self.assertIsInstance(_Role(), ModelBound) + self.assertIs(_Role().llm, adapter) + + +class ModelIdentityValueTest(unittest.TestCase): + """ + Identity is a frozen value so a recorded manifest cannot be mutated after resolution. + """ + + def test_identity_is_immutable(self) -> None: + """ + Assigning to a resolved identity raises rather than rewriting a recorded run. + """ + + identity = ModelIdentity(provider=ModelProvider.GEMINI, model="gemini-3.5-flash") + + with self.assertRaises(ValueError): + identity.model = "swapped" # type: ignore[misc] diff --git a/tests/unit/runtime/qualifier/test_composer.py b/tests/unit/runtime/qualifier/test_composer.py index 000c8112..2ef9bf83 100644 --- a/tests/unit/runtime/qualifier/test_composer.py +++ b/tests/unit/runtime/qualifier/test_composer.py @@ -85,6 +85,7 @@ def __assembly(self, *, api_key: str = "bound-key") -> RunAssemblyBuilder: """ bound_settings = FathomSettings( + _env_file=None, gemini_api_key=api_key, vertex_location="bound-location", vertex_project_id="bound-project", diff --git a/tests/unit/runtime/test_assembly.py b/tests/unit/runtime/test_assembly.py index a1fa9379..b9958e60 100644 --- a/tests/unit/runtime/test_assembly.py +++ b/tests/unit/runtime/test_assembly.py @@ -49,6 +49,7 @@ def test_qualifier_llm_inherits_credentials_from_bound_settings(self) -> None: """ bound_settings = FathomSettings( + _env_file=None, gemini_api_key="test-api-key", vertex_location="bound-location", vertex_project_id="bound-project", diff --git a/tests/unit/runtime/test_builder.py b/tests/unit/runtime/test_builder.py index e33b285c..59432605 100644 --- a/tests/unit/runtime/test_builder.py +++ b/tests/unit/runtime/test_builder.py @@ -5,6 +5,7 @@ from unittest.mock import MagicMock from fathom.adapters.interaction.noop import NoopInteraction +from fathom.constants.manifest import ModelRole, RoleBinding from fathom.constants.storage import StorageBackend from fathom.core.services.qualifier import ( LLMIntentQualifier, @@ -23,6 +24,7 @@ QualifierConfiguration, StorageConfiguration, ) +from fathom.schemas.perception import LocalizationEnsembleConfiguration from fathom.settings.env import FathomSettings @@ -387,3 +389,85 @@ def test_with_storage_port_and_config_reference_the_same_intent(self) -> None: if __name__ == "__main__": unittest.main() + + +class FathomBuilderManifestTest(unittest.TestCase): + """ + A built runner can report which model every role resolved to before a run starts, + so a host can reject an unfair composition instead of scoring it. + """ + + @staticmethod + def __runner(*, planner: LLMPort): + """ + Build a runner over the minimum ports with the supplied planner. + """ + + return ( + Fathom.builder() + .with_llm(port=planner) + .with_device(port=MagicMock(spec=DevicePort)) + .with_perception(port=MagicMock(spec=PerceptionPort)) + .with_interaction(port=NoopInteraction()) + .build() + ) + + def test_manifest_is_absent_until_a_run_resolves_it(self) -> None: + """ + A freshly built runner reports no manifest; it is per-run state, not construction state. + """ + + runner = self.__runner(planner=MagicMock(spec=LLMPort)) + + self.assertIsNone(runner.manifest) + + def test_resolved_manifest_covers_every_role_and_names_the_planner_sharers(self) -> None: + """ + Default composition shares the planner adapter with the qualifier and summarizer. + """ + + planner = MagicMock(spec=LLMPort) + runner = self.__runner(planner=planner) + resolver = runner._FathomRunner__manifest_resolver # type: ignore[attr-defined] + + manifest = resolver.resolve( + steps=50, + localization=LocalizationEnsembleConfiguration(enabled=False, members=()), + ) + + self.assertEqual(len(manifest.roles), len(ModelRole)) + for role in (ModelRole.QUALIFIER, ModelRole.SUMMARIZER, ModelRole.ABORT): + entry = manifest.entry(role=role) + assert entry is not None + self.assertEqual(entry.binding, RoleBinding.SHARED, role.value) + self.assertEqual(entry.source, ModelRole.PLANNER, role.value) + + def test_assembly_composed_qualifier_is_reported_independent(self) -> None: + """ + The dedicated qualifier adapter .with_assembly() builds is not the planner's. + """ + + planner = MagicMock(spec=LLMPort) + runner = ( + Fathom.builder() + .with_llm(port=planner) + .with_device(port=MagicMock(spec=DevicePort)) + .with_perception(port=MagicMock(spec=PerceptionPort)) + .with_assembly( + assembly=RunAssemblyBuilder(settings=FathomSettings(gemini_api_key="test-key")), + llm_factory=_SpyLLMFactory(), + ) + .with_interaction(port=NoopInteraction()) + .build() + ) + resolver = runner._FathomRunner__manifest_resolver # type: ignore[attr-defined] + + manifest = resolver.resolve( + steps=50, + localization=LocalizationEnsembleConfiguration(enabled=False, members=()), + ) + entry = manifest.entry(role=ModelRole.QUALIFIER) + + assert entry is not None + self.assertEqual(entry.binding, RoleBinding.INDEPENDENT) + self.assertIsNone(entry.source) diff --git a/tests/unit/runtime/test_manifest.py b/tests/unit/runtime/test_manifest.py new file mode 100644 index 00000000..9f651696 --- /dev/null +++ b/tests/unit/runtime/test_manifest.py @@ -0,0 +1,637 @@ +"""Verify model-role manifest construction and serialization.""" + +from __future__ import annotations + +import json +import unittest +from typing import Any, Dict, Optional, Sequence +from unittest.mock import MagicMock + +from fathom.adapters.llm.gemini import GeminiLLM +from fathom.adapters.summarization.llm import LLMSummarizer +from fathom.constants.llm import ModelProvider +from fathom.constants.manifest import ( + MANIFEST_VERSION, + SHARED_ARCHITECT_NOTE, + UNDECLARED_BINDING_NOTE, + UNREAD_CONFIGURATION_NOTE, + ModelRole, + RoleBinding, +) +from fathom.core.services.qualifier import LLMIntentQualifier, PermissiveIntentQualifier +from fathom.interfaces.llm import LLMPort, PromptPart +from fathom.interfaces.summarization import SummarizationPort +from fathom.runtime.manifest import ManifestResolver +from fathom.schemas.abort import AbortDetectorConfiguration +from fathom.schemas.configuration import ( + FathomConfiguration, + LLMConfiguration, + OracleConfiguration, + QualifierConfiguration, +) +from fathom.schemas.conversation import ConversationTurn +from fathom.schemas.llm import InferenceSettings, ModelIdentity, StructuredOutput +from fathom.schemas.localization import EnsembleMemberName +from fathom.schemas.manifest import RuntimeManifest +from fathom.schemas.perception import LocalizationEnsembleConfiguration +from fathom.schemas.results import GenerateResult + + +class _StubLLM(LLMPort): + """ + Provider-declaring LLM double whose derive() returns a genuinely distinct sibling. + """ + + def __init__( + self, + *, + model: str = "stub-1", + temperature: float = 1.0, + cache: bool = True, + provider: ModelProvider = ModelProvider.OPENAI, + client: Optional[object] = None, + ) -> None: + """ + Record the identity this double declares and the client it exposes, if any. + """ + + self.__model = model + self.__cache = cache + self.__client = client + self.__provider = provider + self.__temperature = temperature + + @property + def model_name(self) -> str: + """ + Model identifier this double reports. + """ + + return self.__model + + @property + def client(self) -> Optional[object]: + """ + Embedding-capable client this double exposes. + """ + + return self.__client + + @property + def identity(self) -> ModelIdentity: + """ + Declared provider, model, and settings. + """ + + return ModelIdentity( + provider=self.__provider, + model=self.__model, + settings=InferenceSettings(cache=self.__cache, temperature=self.__temperature), + ) + + def derive(self, *, overrides: LLMConfiguration) -> LLMPort: + """ + Return a distinct sibling carrying the overridden temperature and cache setting. + """ + + return _StubLLM( + model=self.__model, + provider=self.__provider, + cache=overrides.use_cache, + temperature=overrides.temperature, + ) + + async def generate( + self, + *, + use_cache: bool, + prompt: Sequence[PromptPart], + tools: Optional[Dict[str, Any]] = None, + system_instruction: Optional[str] = None, + conversation_history: Optional[Sequence[ConversationTurn]] = None, + structured_output: Optional[StructuredOutput] = None, + ) -> GenerateResult: + """ + Unused by manifest resolution. + """ + + raise NotImplementedError + + async def cleanup(self) -> None: + """ + Unused by manifest resolution. + """ + + +class _SelfDerivingLLM(_StubLLM): + """ + LLM double that keeps the port default of returning itself from derive(). + """ + + def derive(self, *, overrides: LLMConfiguration) -> LLMPort: + """ + Return the same instance, as an adapter that has not implemented derive() does. + """ + + return self + + +class _UndeclaredSummarizer(SummarizationPort): + """ + Summarizer double that does not expose the adapter it was composed with. + """ + + async def summarize_trace(self, trace: list) -> str: + """ + Unused by manifest resolution. + """ + + return "" + + +class _ResolverFixture: + """ + Builds a ManifestResolver over chosen ports without standing up a full runner. + """ + + @staticmethod + def build( + *, + planner: LLMPort, + architect: Optional[LLMPort] = None, + qualifier: Optional[object] = None, + summarizer: Optional[object] = None, + configuration: Optional[FathomConfiguration] = None, + ) -> ManifestResolver: + """ + Compose a resolver, defaulting each role to the wiring FathomBuilder produces. + """ + + settings = configuration or FathomConfiguration() + + return ManifestResolver( + planner=planner, + architect=architect + or planner.derive(overrides=LLMConfiguration(temperature=0.0, use_cache=False)), + qualifier=qualifier + or LLMIntentQualifier(llm=planner, configuration=settings.qualifier), + summarizer=summarizer or LLMSummarizer(llm=planner), + configuration=settings, + ) + + @staticmethod + def resolve( + *, + resolver: ManifestResolver, + steps: int = 50, + localization: Optional[LocalizationEnsembleConfiguration] = None, + ) -> RuntimeManifest: + """ + Resolve a manifest, defaulting the ensemble to disabled. + """ + + return resolver.resolve( + steps=steps, + localization=localization + or LocalizationEnsembleConfiguration(enabled=False, members=()), + ) + + +class ManifestPlannerRoleTest(unittest.TestCase): + """ + The planner owns its adapter and its declared identity reaches the manifest verbatim. + """ + + def test_planner_records_declared_provider_model_and_settings(self) -> None: + """ + The planner entry carries the provider, model, and settings the adapter declares. + """ + + planner = _StubLLM(model="gpt-x", provider=ModelProvider.OPENAI, temperature=0.7) + manifest = _ResolverFixture.resolve(resolver=_ResolverFixture.build(planner=planner)) + + entry = manifest.entry(role=ModelRole.PLANNER) + + assert entry is not None and entry.resolved is not None + self.assertEqual(entry.binding, RoleBinding.INDEPENDENT) + self.assertEqual(entry.resolved.provider, ModelProvider.OPENAI) + self.assertEqual(entry.resolved.model, "gpt-x") + self.assertEqual(entry.resolved.settings.temperature, 0.7) + + def test_undeclared_adapter_reports_unknown_provider_not_a_class_name_guess(self) -> None: + """ + An adapter that declares nothing yields UNKNOWN, never a name derived from its class. + """ + + planner = MagicMock(spec=LLMPort) + planner.model_name = "whatever" + manifest = _ResolverFixture.resolve( + resolver=_ResolverFixture.build(planner=planner, architect=planner) + ) + + entry = manifest.entry(role=ModelRole.PLANNER) + + assert entry is not None + self.assertIsNone(entry.resolved) + + +class ManifestArchitectDerivationTest(unittest.TestCase): + """ + Regression: the manifest must separate a real deterministic sibling from a self-returning + derive(), because the second silently runs decomposition at the planner's temperature. + """ + + def test_distinct_sibling_is_derived_and_carries_the_deterministic_settings(self) -> None: + """ + A derive() that returns a new adapter yields DERIVED with temperature 0.0 and no cache. + """ + + planner = _StubLLM(temperature=1.0, cache=True) + manifest = _ResolverFixture.resolve(resolver=_ResolverFixture.build(planner=planner)) + + entry = manifest.entry(role=ModelRole.ARCHITECT) + + assert entry is not None and entry.resolved is not None + self.assertEqual(entry.binding, RoleBinding.DERIVED) + self.assertEqual(entry.resolved.settings.temperature, 0.0) + self.assertFalse(entry.resolved.settings.cache) + self.assertIsNone(entry.note) + + def test_self_returning_derive_is_shared_and_keeps_the_planner_settings(self) -> None: + """ + A derive() that returns the planner yields SHARED, temperature 1.0, and an explicit note. + """ + + planner = _SelfDerivingLLM(temperature=1.0, cache=True) + manifest = _ResolverFixture.resolve(resolver=_ResolverFixture.build(planner=planner)) + + entry = manifest.entry(role=ModelRole.ARCHITECT) + + assert entry is not None and entry.resolved is not None + self.assertEqual(entry.binding, RoleBinding.SHARED) + self.assertEqual(entry.source, ModelRole.PLANNER) + self.assertEqual(entry.resolved.settings.temperature, 1.0) + self.assertTrue(entry.resolved.settings.cache) + self.assertEqual(entry.note, SHARED_ARCHITECT_NOTE) + + def test_the_two_derive_behaviours_produce_different_manifests(self) -> None: + """ + The serialized architect entries differ, so the difference cannot be read past. + """ + + derived = _ResolverFixture.resolve( + resolver=_ResolverFixture.build(planner=_StubLLM()) + ).entry(role=ModelRole.ARCHITECT) + shared = _ResolverFixture.resolve( + resolver=_ResolverFixture.build(planner=_SelfDerivingLLM()) + ).entry(role=ModelRole.ARCHITECT) + + assert derived is not None and shared is not None + self.assertNotEqual(derived.model_dump(mode="json"), shared.model_dump(mode="json")) + + +class ManifestQualifierRoleTest(unittest.TestCase): + """ + The qualifier is only independent when composition gave it a dedicated adapter. + """ + + def test_qualifier_reusing_the_planner_is_shared_and_says_so(self) -> None: + """ + A qualifier composed on the planner adapter reports SHARED sourced from PLANNER. + """ + + planner = _StubLLM() + manifest = _ResolverFixture.resolve(resolver=_ResolverFixture.build(planner=planner)) + + entry = manifest.entry(role=ModelRole.QUALIFIER) + + assert entry is not None and entry.requested is not None + self.assertEqual(entry.binding, RoleBinding.SHARED) + self.assertEqual(entry.source, ModelRole.PLANNER) + self.assertEqual(entry.requested.model, QualifierConfiguration().inference.model) + self.assertIsNotNone(entry.note) + + def test_dedicated_qualifier_adapter_is_independent(self) -> None: + """ + A qualifier composed on its own adapter reports INDEPENDENT with that adapter's model. + """ + + planner = _StubLLM(model="planner-1") + dedicated = _StubLLM(model="qualifier-lite", temperature=0.0) + manifest = _ResolverFixture.resolve( + resolver=_ResolverFixture.build( + planner=planner, + qualifier=LLMIntentQualifier(llm=dedicated), + ) + ) + + entry = manifest.entry(role=ModelRole.QUALIFIER) + + assert entry is not None and entry.resolved is not None + self.assertEqual(entry.binding, RoleBinding.INDEPENDENT) + self.assertIsNone(entry.source) + self.assertEqual(entry.resolved.model, "qualifier-lite") + self.assertEqual(entry.resolved.settings.temperature, 0.0) + + def test_disabled_qualifier_is_reported_disabled_with_no_adapter(self) -> None: + """ + With qualifier.enabled=False the role is NONE, has no resolved adapter, and keeps the request. + """ + + configuration = FathomConfiguration(qualifier=QualifierConfiguration(enabled=False)) + manifest = _ResolverFixture.resolve( + resolver=_ResolverFixture.build( + planner=_StubLLM(), + qualifier=PermissiveIntentQualifier(), + configuration=configuration, + ) + ) + + entry = manifest.entry(role=ModelRole.QUALIFIER) + + assert entry is not None and entry.requested is not None + self.assertFalse(entry.enabled) + self.assertEqual(entry.binding, RoleBinding.NONE) + self.assertIsNone(entry.resolved) + self.assertEqual(entry.requested.model, QualifierConfiguration().inference.model) + + +class ManifestUndeclaredBindingTest(unittest.TestCase): + """ + A port that hides its adapter is reported as undeclared, never assumed independent. + """ + + def test_summarizer_without_the_capability_reports_unknown_binding(self) -> None: + """ + A third-party summarizer yields UNKNOWN rather than a false claim of independence. + """ + + manifest = _ResolverFixture.resolve( + resolver=_ResolverFixture.build( + planner=_StubLLM(), + summarizer=_UndeclaredSummarizer(), + ) + ) + + entry = manifest.entry(role=ModelRole.SUMMARIZER) + + assert entry is not None + self.assertEqual(entry.binding, RoleBinding.UNKNOWN) + self.assertEqual(entry.note, UNDECLARED_BINDING_NOTE) + self.assertIsNone(entry.resolved) + + def test_default_summarizer_shares_the_planner_adapter(self) -> None: + """ + The summarizer FathomBuilder installs runs on the planner adapter. + """ + + planner = _StubLLM(model="planner-1") + manifest = _ResolverFixture.resolve(resolver=_ResolverFixture.build(planner=planner)) + + entry = manifest.entry(role=ModelRole.SUMMARIZER) + + assert entry is not None and entry.resolved is not None + self.assertEqual(entry.binding, RoleBinding.SHARED) + self.assertEqual(entry.source, ModelRole.PLANNER) + self.assertEqual(entry.resolved.model, "planner-1") + + +class ManifestOptionalRoleTest(unittest.TestCase): + """ + Abort, oracle, localizer, and embedder each report the enablement composition gives them. + """ + + def test_abort_detector_records_the_configured_model_it_never_uses(self) -> None: + """ + The abort role resolves to the planner adapter while requesting a different model. + """ + + planner = _StubLLM(model="planner-1") + manifest = _ResolverFixture.resolve(resolver=_ResolverFixture.build(planner=planner)) + + entry = manifest.entry(role=ModelRole.ABORT) + + assert entry is not None and entry.resolved is not None and entry.requested is not None + self.assertTrue(entry.enabled) + self.assertEqual(entry.binding, RoleBinding.SHARED) + self.assertEqual(entry.resolved.model, "planner-1") + self.assertEqual(entry.requested.model, AbortDetectorConfiguration().inference.model) + self.assertNotEqual(entry.requested.model, entry.resolved.model) + self.assertEqual(entry.note, UNREAD_CONFIGURATION_NOTE) + + def test_oracle_follows_its_configuration_flag(self) -> None: + """ + The oracle is SHARED when configuration enables it and NONE when it does not. + """ + + planner = _StubLLM() + enabled = _ResolverFixture.resolve( + resolver=_ResolverFixture.build( + planner=planner, + configuration=FathomConfiguration(oracle=OracleConfiguration(enabled=True)), + ) + ).entry(role=ModelRole.ORACLE) + disabled = _ResolverFixture.resolve( + resolver=_ResolverFixture.build( + planner=planner, + configuration=FathomConfiguration(oracle=OracleConfiguration(enabled=False)), + ) + ).entry(role=ModelRole.ORACLE) + + assert enabled is not None and disabled is not None + self.assertTrue(enabled.enabled) + self.assertEqual(enabled.binding, RoleBinding.SHARED) + self.assertFalse(disabled.enabled) + self.assertEqual(disabled.binding, RoleBinding.NONE) + self.assertIsNone(disabled.resolved) + + def test_localizer_enabled_only_when_its_ensemble_member_is_configured(self) -> None: + """ + The vision localizer needs both the ensemble enabled and its member present. + """ + + resolver = _ResolverFixture.build(planner=_StubLLM()) + + active = _ResolverFixture.resolve( + resolver=resolver, + localization=LocalizationEnsembleConfiguration( + enabled=True, + members=(EnsembleMemberName.GEMINI_VISION,), + ), + ).entry(role=ModelRole.LOCALIZER) + without_member = _ResolverFixture.resolve( + resolver=resolver, + localization=LocalizationEnsembleConfiguration( + enabled=True, + members=(EnsembleMemberName.DOCUMENT_AI_LAYOUT,), + ), + ).entry(role=ModelRole.LOCALIZER) + + assert active is not None and without_member is not None + self.assertTrue(active.enabled) + self.assertEqual(active.binding, RoleBinding.SHARED) + self.assertFalse(without_member.enabled) + self.assertEqual(without_member.binding, RoleBinding.NONE) + + def test_provider_neutral_localizer_member_is_supported(self) -> None: + """The provider-neutral member name enables the bound planner localizer.""" + + entry = _ResolverFixture.resolve( + resolver=_ResolverFixture.build(planner=_StubLLM()), + localization=LocalizationEnsembleConfiguration( + enabled=True, + members=(EnsembleMemberName.VISION_LLM,), + ), + ).entry(role=ModelRole.LOCALIZER) + + assert entry is not None + self.assertTrue(entry.enabled) + self.assertEqual(entry.binding, RoleBinding.SHARED) + + def test_embedder_enabled_only_when_the_planner_exposes_a_client(self) -> None: + """ + The embedder role tracks whether the planner adapter can back a sibling embedding adapter. + """ + + with_client = _ResolverFixture.resolve( + resolver=_ResolverFixture.build(planner=_StubLLM(client=object())) + ).entry(role=ModelRole.EMBEDDER) + without_client = _ResolverFixture.resolve( + resolver=_ResolverFixture.build(planner=_StubLLM(client=None)) + ).entry(role=ModelRole.EMBEDDER) + + assert with_client is not None and without_client is not None + self.assertTrue(with_client.enabled) + self.assertEqual(with_client.binding, RoleBinding.SHARED) + self.assertFalse(without_client.enabled) + self.assertEqual(without_client.binding, RoleBinding.NONE) + + +class ManifestSerializationTest(unittest.TestCase): + """ + The manifest is JSON-serializable, stable across resolutions, and carries no secrets. + """ + + @staticmethod + def __credentialed_planner() -> _StubLLM: + """ + Planner whose model string embeds values a leak would surface. + """ + + return _StubLLM(model="planner-1", provider=ModelProvider.GEMINI) + + def test_manifest_serializes_to_json_with_every_role_and_the_step_budget(self) -> None: + """ + Serialization yields the version, the effective step budget, and all eight roles. + """ + + manifest = _ResolverFixture.resolve( + resolver=_ResolverFixture.build(planner=self.__credentialed_planner()), + steps=37, + ) + payload = json.loads(json.dumps(manifest.model_dump(mode="json"))) + + self.assertEqual(payload["version"], MANIFEST_VERSION) + self.assertEqual(payload["steps"], 37) + self.assertEqual( + [entry["role"] for entry in payload["roles"]], + [role.value for role in ModelRole], + ) + + def test_repeated_resolution_produces_an_identical_payload(self) -> None: + """ + Two resolutions of the same composition serialize identically. + """ + + resolver = _ResolverFixture.build(planner=self.__credentialed_planner()) + + first = _ResolverFixture.resolve(resolver=resolver, steps=12) + second = _ResolverFixture.resolve(resolver=resolver, steps=12) + + self.assertEqual( + json.dumps(first.model_dump(mode="json"), sort_keys=True), + json.dumps(second.model_dump(mode="json"), sort_keys=True), + ) + + @staticmethod + def __credentialed_gemini() -> GeminiLLM: + """ + Bind a credentialed configuration to a Gemini adapter without building an SDK client. + + Client construction validates service-account material against the Google SDK and is + irrelevant to what ``identity`` exposes, which is the surface under test here. + """ + + gemini = object.__new__(GeminiLLM) + gemini._GeminiLLM__client = None # type: ignore[attr-defined] + gemini._GeminiLLM__configuration = LLMConfiguration( # type: ignore[attr-defined] + api_key="super-secret-key", + model="gemini-3.5-flash", + project_id="secret-project", + location="secret-location", + credentials={"type": "service_account", "private_key": "-----BEGIN PRIVATE KEY"}, + ) + return gemini + + def test_serialized_manifest_carries_no_credentials(self) -> None: + """ + A planner bound to a credentialed configuration leaks no key, project, or credential. + """ + + planner = self.__credentialed_gemini() + manifest = _ResolverFixture.resolve( + resolver=_ResolverFixture.build(planner=planner, architect=planner) + ) + payload = json.dumps(manifest.model_dump(mode="json")) + + self.assertNotIn("super-secret-key", payload) + self.assertNotIn("secret-project", payload) + self.assertNotIn("secret-location", payload) + self.assertNotIn("BEGIN PRIVATE KEY", payload) + self.assertNotIn("service_account", payload) + self.assertIn("gemini-3.5-flash", payload) + + def test_manifest_exposes_only_its_declared_fields(self) -> None: + """ + No prompt, screenshot, or user-entered value can ride along: the shape is closed. + + Structural guard — a future field carrying run content fails here before it ships. + """ + + manifest = _ResolverFixture.resolve( + resolver=_ResolverFixture.build(planner=self.__credentialed_planner()) + ) + payload = manifest.model_dump(mode="json") + + self.assertEqual(set(payload), {"version", "steps", "roles"}) + self.assertEqual( + set(payload["roles"][0]), + {"role", "enabled", "binding", "source", "requested", "resolved", "note"}, + ) + self.assertEqual( + set(payload["roles"][0]["resolved"]), + {"provider", "model", "settings"}, + ) + self.assertEqual( + set(payload["roles"][0]["resolved"]["settings"]), + {"cache", "thinking", "temperature"}, + ) + + def test_providers_reports_each_distinct_resolved_provider(self) -> None: + """ + A composition mixing two providers reports both, once each. + """ + + planner = _StubLLM(model="planner-1", provider=ModelProvider.OPENAI) + dedicated = _StubLLM(model="qualifier-1", provider=ModelProvider.ANTHROPIC) + manifest = _ResolverFixture.resolve( + resolver=_ResolverFixture.build( + planner=planner, + qualifier=LLMIntentQualifier(llm=dedicated), + ) + ) + + self.assertEqual( + manifest.providers(), + (ModelProvider.OPENAI, ModelProvider.ANTHROPIC), + ) diff --git a/tests/unit/runtime/test_runner.py b/tests/unit/runtime/test_runner.py index f87aafc0..83171bc3 100644 --- a/tests/unit/runtime/test_runner.py +++ b/tests/unit/runtime/test_runner.py @@ -1,13 +1,26 @@ from __future__ import annotations +import json import unittest from datetime import datetime, timezone -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, MagicMock +from fathom.adapters.interaction.noop import NoopInteraction from fathom.constants.collaboration import TaskCode +from fathom.constants.llm import ModelProvider +from fathom.constants.manifest import ModelRole +from fathom.constants.qualification import QualificationLabel, RationaleCategory from fathom.constants.state import CompletionReason +from fathom.core.config.loader import RuntimeConfigLoader +from fathom.interfaces.device import DevicePort +from fathom.interfaces.llm import LLMPort +from fathom.interfaces.perception import PerceptionPort +from fathom.runtime.builder import Fathom from fathom.runtime.runner import FathomRunner +from fathom.schemas.llm import ModelIdentity +from fathom.schemas.qualification import QualificationVerdict, Rationale from fathom.schemas.recording import Handle, ScriptOutput +from fathom.settings.env import FathomSettings class FathomRunnerGeneratedScriptTest(unittest.IsolatedAsyncioTestCase): @@ -206,3 +219,190 @@ def test_reserve_execution_never_consults_the_recorder(self) -> None: self.assertFalse(hasattr(runner, "_FathomRunner__recorder")) self.assertTrue(reserve(execution_id=None, workflow_id="workflow-1")) + + +class FathomRunnerManifestEmissionTest(unittest.TestCase): + """ + The runner resolves the model-role manifest at run start, records it for the host to read, + and emits it as one structured event. + """ + + @staticmethod + def __runner(*, planner: LLMPort) -> FathomRunner: + """ + Build a runner over the minimum ports needed to resolve a manifest. + """ + + return ( + Fathom.builder() + .with_llm(port=planner) + .with_device(port=MagicMock(spec=DevicePort)) + .with_perception(port=MagicMock(spec=PerceptionPort)) + .with_interaction(port=NoopInteraction()) + .build() + ) + + @staticmethod + def __loader() -> RuntimeConfigLoader: + """ + Loader bound to explicit settings so the manifest never depends on ambient env. + """ + + return RuntimeConfigLoader(settings=FathomSettings(ensemble_localizer_enabled=False)) + + def test_resolution_records_the_manifest_on_the_runner(self) -> None: + """ + After resolution the runner exposes the manifest with the effective step budget. + """ + + runner = self.__runner(planner=MagicMock(spec=LLMPort)) + resolve = runner._FathomRunner__resolve_manifest # type: ignore[attr-defined] + + returned = resolve(steps=17, loader=self.__loader()) + + self.assertIs(runner.manifest, returned) + self.assertEqual(returned.steps, 17) + + def test_resolution_emits_one_structured_manifest_event(self) -> None: + """ + The run-start event carries the serialized manifest under a stable event name. + """ + + runner = self.__runner(planner=MagicMock(spec=LLMPort)) + resolve = runner._FathomRunner__resolve_manifest # type: ignore[attr-defined] + + with self.assertLogs("fathom.runtime.runner", level="INFO") as captured: + resolve(steps=9, loader=self.__loader()) + + events = [ + record + for record in captured.records + if getattr(record, "event", None) == "fathom.manifest.resolved" + ] + self.assertEqual(len(events), 1) + self.assertEqual(events[0].manifest["steps"], 9) # type: ignore[attr-defined] + self.assertEqual( + [entry["role"] for entry in events[0].manifest["roles"]], # type: ignore[attr-defined] + [role.value for role in ModelRole], + ) + + def test_recorded_provider_comes_from_the_declared_identity(self) -> None: + """ + Regression: the recorded provider is what the adapter declares, not its class name. + + A class named ``StubPlanner`` would have been recorded as "stubplanner" by the previous + class-name derivation; the declared identity is the only source now. + """ + + planner = MagicMock(spec=LLMPort) + planner.identity = ModelIdentity( + provider=ModelProvider.ANTHROPIC, + model="claude-x", + ) + runner = self.__runner(planner=planner) + + provider = runner._FathomRunner__llm_provider() # type: ignore[attr-defined] + + self.assertEqual(provider, "anthropic") + + def test_undeclared_adapter_records_unknown_rather_than_a_guess(self) -> None: + """ + An adapter that declares no identity is recorded as unknown. + """ + + runner = self.__runner(planner=MagicMock(spec=LLMPort)) + + provider = runner._FathomRunner__llm_provider() # type: ignore[attr-defined] + + self.assertEqual(provider, ModelProvider.UNKNOWN.value) + + +class FathomRunnerRejectedRunManifestTest(unittest.IsolatedAsyncioTestCase): + """ + A run the qualifier rejects still reports which models were composed, so a host can tell + a rejection apart from a harness misconfiguration. + """ + + async def test_rejection_result_carries_the_runs_manifest(self) -> None: + """ + The terminal rejection result carries the manifest resolved for that run. + """ + + runner = ( + Fathom.builder() + .with_llm(port=MagicMock(spec=LLMPort)) + .with_device(port=MagicMock(spec=DevicePort)) + .with_perception(port=MagicMock(spec=PerceptionPort)) + .with_telemetry(port=AsyncMock()) + .with_interaction(port=NoopInteraction()) + .build() + ) + resolve = runner._FathomRunner__resolve_manifest # type: ignore[attr-defined] + build = runner._FathomRunner__build_rejection_result # type: ignore[attr-defined] + manifest = resolve( + steps=25, + loader=RuntimeConfigLoader(settings=FathomSettings(ensemble_localizer_enabled=False)), + ) + + result = await build( + intent="pay the invoice", + workflow_id="workflow-1", + start_time=0.0, + manifest=manifest, + verdict=QualificationVerdict( + confidence=1.0, + message="Cannot run that.", + label=QualificationLabel.NOT_EXECUTABLE, + rationale=Rationale( + category=RationaleCategory.EMPTY, + reasoning="empty", + ), + ), + verdict_payload={}, + ) + + assert result.manifest is not None + self.assertIs(result.manifest, manifest) + self.assertEqual(result.manifest.steps, 25) + self.assertEqual(result.completion_reason, CompletionReason.NOT_EXECUTABLE.value) + + async def test_rejection_result_manifest_never_leaks_the_intent(self) -> None: + """ + The manifest attached to a rejected run carries no trace of the user's intent text. + """ + + runner = ( + Fathom.builder() + .with_llm(port=MagicMock(spec=LLMPort)) + .with_device(port=MagicMock(spec=DevicePort)) + .with_perception(port=MagicMock(spec=PerceptionPort)) + .with_telemetry(port=AsyncMock()) + .with_interaction(port=NoopInteraction()) + .build() + ) + resolve = runner._FathomRunner__resolve_manifest # type: ignore[attr-defined] + build = runner._FathomRunner__build_rejection_result # type: ignore[attr-defined] + + result = await build( + intent="transfer 500 to account 12345", + workflow_id="workflow-1", + start_time=0.0, + manifest=resolve( + steps=25, + loader=RuntimeConfigLoader( + settings=FathomSettings(ensemble_localizer_enabled=False) + ), + ), + verdict=QualificationVerdict( + confidence=1.0, + message=None, + label=QualificationLabel.NOT_EXECUTABLE, + rationale=Rationale(category=RationaleCategory.EMPTY, reasoning="empty"), + ), + verdict_payload={}, + ) + + assert result.manifest is not None + payload = json.dumps(result.manifest.model_dump(mode="json")) + self.assertNotIn("12345", payload) + self.assertNotIn("transfer", payload) diff --git a/tests/unit/strategies/intent/test_intent.py b/tests/unit/strategies/intent/test_intent.py index 01e98a3f..b4786c84 100644 --- a/tests/unit/strategies/intent/test_intent.py +++ b/tests/unit/strategies/intent/test_intent.py @@ -110,10 +110,10 @@ async def test_adapter_passes_fathom_serde_with_allowed_modules(self) -> None: async with store.open(workflow_id="workflow-allowlist-test") as checkpointer: self.assertEqual(type(checkpointer).__name__, "AsyncSqliteSaver") self.assertEqual(type(checkpointer.serde).__name__, "JsonPlusSerializer") - allowed_modules = getattr( - checkpointer.serde, - "_allowed_json_modules", - checkpointer.serde._allowed_modules, + allowed_modules = ( + checkpointer.serde._allowed_json_modules + if hasattr(checkpointer.serde, "_allowed_json_modules") + else checkpointer.serde._allowed_modules ) self.assertEqual(allowed_modules, set(CHECKPOINT_ALLOWED_JSON_MODULES)) if hasattr(checkpointer.serde, "_allowed_msgpack_modules"):