Foundational abstractions and utilities underpinning the pipeline: phase runner protocols, recursive
component discovery/fingerprinting, run fingerprint functions, and the artifact dependency graph used for
cross-run invalidation diffing.
Base for every pipeline phase. Each phase accepts a typed input contract
and returns an artifact collection. Phases may still project to the graph incrementally for crash resilience, but artifact collections are the runtime handoff.
The Pipeline class composes PhaseRunner instances into a DAG and exposes
.run(), .run_phase(n), and .run_from_phase(n).
The orchestrator needs three things from a phase that name cannot
safely supply: which config block to fingerprint, whether to persist its
artifacts, and which artifact view to feed it. Those used to be recovered
by string-matching name (name.startswith("Phase 3b")), which made a
display string load-bearing — renaming a phase silently changed its
behaviour, and the match order mattered ("Phase 3b" had to be tested before
"Phase 3"). They are now explicit class attributes.
Source code in packages/episteme-pipeline/episteme_pipeline/protocols/phase_runner.py
classPhaseRunner[InputT](ABC):""" Base for every pipeline phase. Each phase accepts a typed input contract and returns an artifact collection. Phases may still project to the graph incrementally for crash resilience, but artifact collections are the runtime handoff. The Pipeline class composes PhaseRunner instances into a DAG and exposes .run(), .run_phase(n), and .run_from_phase(n). Dispatch contract (O-09) ------------------------ The orchestrator needs three things from a phase that ``name`` cannot safely supply: which config block to fingerprint, whether to persist its artifacts, and which artifact view to feed it. Those used to be recovered by string-matching ``name`` (``name.startswith("Phase 3b")``), which made a display string load-bearing — renaming a phase silently changed its behaviour, and the match order mattered ("Phase 3b" had to be tested before "Phase 3"). They are now explicit class attributes. """#: Human-readable phase name. **Display only** — appears in manifests,#: reports and logs. Never dispatch on it.name:ClassVar[str]#: Stable machine key for this phase. Part of the orchestrator contract:#: the phase's config block is ``getattr(PipelineConfig, phase_key)`` and#: its persistence toggle is#: ``getattr(ExecutionConfig, f"persist_{phase_key}_artifacts")``.#: ``Pipeline.__init__`` validates both, so a typo fails at composition#: time rather than silently selecting the wrong config.phase_key:ClassVar[str]#: Artifact view class this phase consumes, e.g. ``Phase1ArtifactsView``.#: ``None`` means the phase is fed the raw ``PipelineInput`` — Phase 1 only.input_view:ClassVar[type|None]=None@abstractmethodasyncdefrun(self,input:InputT,context:ArtifactExecutionContext)->ArtifactCollection:...defcomponents(self)->dict[str,object]:"""Discover all injected computational components attached to this runner. Recursively inspects runner attributes to discover objects implementing the ``Fingerprintable`` protocol, LLM facades, embedders, decision engines, and classifiers. Returns ------- dict of str to object Mapping from dotted hierarchical path to component instances. """fromepisteme_pipeline.protocols.fingerprintimportfind_componentsreturnfind_components(self)
dict of str to object
Mapping from dotted hierarchical path to component instances.
Source code in packages/episteme-pipeline/episteme_pipeline/protocols/phase_runner.py
505152535455565758596061626364
defcomponents(self)->dict[str,object]:"""Discover all injected computational components attached to this runner. Recursively inspects runner attributes to discover objects implementing the ``Fingerprintable`` protocol, LLM facades, embedders, decision engines, and classifiers. Returns ------- dict of str to object Mapping from dotted hierarchical path to component instances. """fromepisteme_pipeline.protocols.fingerprintimportfind_componentsreturnfind_components(self)
Recursively discovers the injected computational components of a phase (via find_components), producing
hierarchical dotted keys for method/model/engine fingerprinting.
Discover all injected computational components attached to this runner.
Recursively inspects runner attributes to discover objects implementing
the Fingerprintable protocol, LLM facades, embedders, decision engines,
and classifiers.
dict of str to object
Mapping from dotted hierarchical path to component instances.
Source code in packages/episteme-pipeline/episteme_pipeline/protocols/phase_runner.py
505152535455565758596061626364
defcomponents(self)->dict[str,object]:"""Discover all injected computational components attached to this runner. Recursively inspects runner attributes to discover objects implementing the ``Fingerprintable`` protocol, LLM facades, embedders, decision engines, and classifiers. Returns ------- dict of str to object Mapping from dotted hierarchical path to component instances. """fromepisteme_pipeline.protocols.fingerprintimportfind_componentsreturnfind_components(self)
Protocol for components that expose deterministic state for cache invalidation and run reuse.
Bases: Protocol
Protocol for components that expose deterministic state for cache invalidation.
Any computational unit, model adapter, decision engine, or extractor whose
behavior affects pipeline outputs should satisfy this protocol by returning
a JSON-serializable dictionary, list, or string representing its configuration,
weights revision, or hyperparameters.
Source code in packages/episteme-pipeline/episteme_pipeline/protocols/fingerprint.py
4748495051525354555657585960616263646566
@runtime_checkableclassFingerprintable(Protocol):"""Protocol for components that expose deterministic state for cache invalidation. Any computational unit, model adapter, decision engine, or extractor whose behavior affects pipeline outputs should satisfy this protocol by returning a JSON-serializable dictionary, list, or string representing its configuration, weights revision, or hyperparameters. """deffingerprint(self)->Any:"""Return a deterministic JSON-serializable representation of component state. Returns ------- Any JSON-serializable dictionary, list, string, or primitive representing the component's identity, hyperparameters, and internal state. """...
Any
JSON-serializable dictionary, list, string, or primitive representing
the component's identity, hyperparameters, and internal state.
Source code in packages/episteme-pipeline/episteme_pipeline/protocols/fingerprint.py
57585960616263646566
deffingerprint(self)->Any:"""Return a deterministic JSON-serializable representation of component state. Returns ------- Any JSON-serializable dictionary, list, string, or primitive representing the component's identity, hyperparameters, and internal state. """...
Recursively traverses an object graph (DFS) to discover nested computational components under hierarchical
dotted paths (à la PyTorch's nn.Module).
Recursively discover all computational components in an object graph.
Traverses object attributes, lists, and dictionaries using Depth-First Search
(DFS) to build hierarchical dotted paths (e.g. global_extractor.reranker),
similar to PyTorch's named_modules().
root : Any
Root object to introspect (e.g., a PhaseRunner instance or extractor).
prefix : str, default ""
Current path prefix for hierarchical component keys.
visited : set of int or None, default None
Set of visited object memory IDs to avoid reference cycles.
deffind_components(root:Any,prefix:str="",visited:set[int]|None=None,)->dict[str,Any]:"""Recursively discover all computational components in an object graph. Traverses object attributes, lists, and dictionaries using Depth-First Search (DFS) to build hierarchical dotted paths (e.g. ``global_extractor.reranker``), similar to PyTorch's ``named_modules()``. Parameters ---------- root : Any Root object to introspect (e.g., a PhaseRunner instance or extractor). prefix : str, default "" Current path prefix for hierarchical component keys. visited : set of int or None, default None Set of visited object memory IDs to avoid reference cycles. Returns ------- dict of str to Any Mapping from dotted component path to the discovered component instance. """ifvisitedisNone:visited=set()ifrootisNoneorid(root)invisited:return{}ifisinstance(root,(_PRIMITIVE_TYPES,list,tuple,set,dict,NonCallableMock)):return{}visited.add(id(root))discovered:dict[str,Any]={}# Extract instance attributesraw_dict=getattr(root,"__dict__",None)ifnotisinstance(raw_dict,dict):return{}attrs={k:vfork,vinraw_dict.items()ifisinstance(k,str)andnotk.startswith("_")}forname,valueinattrs.items():ifvalueisNone:continuefull_path=f"{prefix}.{name}"ifprefixelsenameifis_component(value,attr_name=name):discovered[full_path]=valueifnotisinstance(value,(list,tuple,dict)):discovered.update(find_components(value,prefix=full_path,visited=visited))elifisinstance(value,(list,tuple)):fori,iteminenumerate(value):sub_path=f"{full_path}[{i}]"ifis_component(item):discovered[sub_path]=itemdiscovered.update(find_components(item,prefix=sub_path,visited=visited))elifisinstance(value,dict):fork,iteminvalue.items():ifisinstance(k,str)andnotk.startswith("_"):sub_path=f"{full_path}.{k}"ifis_component(item):discovered[sub_path]=itemdiscovered.update(find_components(item,prefix=sub_path,visited=visited))returndiscovered
defis_component(val:Any,attr_name:str|None=None)->bool:"""Check if an object qualifies as a computational component for fingerprinting. Parameters ---------- val : Any Candidate object to evaluate. attr_name : str or None, optional Attribute name under which the object is bound on its parent. Returns ------- bool True if the object is an eligible component, False otherwise. """ifvalisNoneorisinstance(val,_PRIMITIVE_TYPES):returnFalse# Explicit protocol conformance (structural typing)ifisinstance(val,Fingerprintable)andcallable(getattr(val,"fingerprint",None)):returnTrue# Pydantic models (configs, schemas, data contracts) are fingerprinted separatelyifisinstance(val,BaseModel):returnFalse# Core runner component attributes (backwards compatibility for test doubles)returnattr_namein_CORE_COMPONENT_NAMES
Deterministic SHA-256 hashing primitives generated by pipeline/runs/fingerprints.py and used to build the
run manifest fingerprints for pre-execution phase reuse.
Compute fine-grained nested config fingerprints per leaf field.
Unlike fingerprint_phase_config which serializes the entire config
as one blob, this computes a separate stable fingerprint for each
leaf field in the config. This lets invalidation detect which
specific leaf changed rather than just that "the config changed".
Source code in packages/episteme-pipeline/episteme_pipeline/runs/fingerprints.py
525354555657585960616263646566676869707172
deffingerprint_phase_config_nested(config:Any)->dict[str,str]:"""Compute fine-grained nested config fingerprints per leaf field. Unlike `fingerprint_phase_config` which serializes the entire config as one blob, this computes a separate stable fingerprint for each leaf field in the config. This lets invalidation detect which specific leaf changed rather than just that "the config changed". """ifhasattr(config,"model_dump"):dumped=config.model_dump(mode="json")else:dumped:dict[str,Any]={}phase_dict=getattr(config,"__dict__",None)ifisinstance(phase_dict,dict):forkey,valueinphase_dict.items():ifhasattr(value,"model_dump"):dumped[key]=value.model_dump(mode="json")elif_is_fully_serializable(value):dumped[key]=valuereturn_fingerprint_nested_leafs(dumped,prefix="")
Compute a fingerprint for a method object (e.g., LLM, embedding model, extractor).
Prefers an explicit contract: if the object exposes fingerprint()
returning a JSON-serialisable value, that value is the fingerprint input.
Implement it on any component whose behaviour depends on state this module
cannot see — a SentenceTransformer revision, a quantisation setting, a
reranker's activation function.
Otherwise this falls back to probing a fixed list of well-known attributes
(model name, temperature, max_tokens, dimensions, …). That fallback is
best-effort and silently incomplete by construction (O-15): anything not on
the list is invisible to invalidation, so a run can be reused after a change
that should have invalidated it.
Returns None if the object is None or exposes nothing recognisable.
Source code in packages/episteme-pipeline/episteme_pipeline/runs/fingerprints.py
deffingerprint_method(method_obj:Any)->str|None:"""Compute a fingerprint for a method object (e.g., LLM, embedding model, extractor). Prefers an explicit contract: if the object exposes ``fingerprint()`` returning a JSON-serialisable value, that value *is* the fingerprint input. Implement it on any component whose behaviour depends on state this module cannot see — a SentenceTransformer revision, a quantisation setting, a reranker's activation function. Otherwise this falls back to probing a fixed list of well-known attributes (model name, temperature, max_tokens, dimensions, …). That fallback is best-effort and silently incomplete by construction (O-15): anything not on the list is invisible to invalidation, so a run can be reused after a change that should have invalidated it. Returns None if the object is None or exposes nothing recognisable. """ifmethod_objisNone:returnNoneexplicit=getattr(method_obj,"fingerprint",None)ifcallable(explicit):try:value=explicit()if_is_fully_serializable(value):returnstable_fingerprint({"class":method_obj.__class__.__name__,"fingerprint":value})exceptExceptionasex:logger.exception(ex)fingerprint_data:dict[str,Any]={"class":method_obj.__class__.__name__}model_name=getattr(method_obj,"model_name",None)ifmodel_name:fingerprint_data["model"]=str(model_name)model_name_or_provider=getattr(method_obj,"model_name_or_provider",None)ifmodel_name_or_provider:fingerprint_data["model_provider"]=str(model_name_or_provider)model=getattr(method_obj,"model",None)ifmodelisnotNone:fingerprint_data["model_ref"]=str(model)# API version detection — important for LLM API changesapi_version=getattr(method_obj,"api_version",None)ifapi_versionisnotNoneand_is_fully_serializable(api_version):fingerprint_data["api_version"]=str(api_version)# Provider/endpoint configurationbase_url=getattr(method_obj,"base_url",None)ifbase_urlisnotNoneand_is_fully_serializable(base_url):fingerprint_data["base_url"]=str(base_url)# Runtime parameters that affect model outputtemperature=getattr(method_obj,"temperature",None)iftemperatureisnotNoneand_is_fully_serializable(temperature):fingerprint_data["temperature"]=temperaturemax_tokens=getattr(method_obj,"max_tokens",None)ifmax_tokensisnotNoneand_is_fully_serializable(max_tokens):fingerprint_data["max_tokens"]=max_tokenstop_p=getattr(method_obj,"top_p",None)iftop_pisnotNoneand_is_fully_serializable(top_p):fingerprint_data["top_p"]=top_pn=getattr(method_obj,"n",None)ifnisnotNoneand_is_fully_serializable(n):fingerprint_data["n"]=n# Embedding-specific parametersdimensions=getattr(method_obj,"dimensions",None)ifdimensionsisnotNoneand_is_fully_serializable(dimensions):fingerprint_data["dimensions"]=dimensionsembedding_api_version=getattr(method_obj,"embedding_api_version",None)ifembedding_api_versionisnotNoneand_is_fully_serializable(embedding_api_version):fingerprint_data["embedding_api_version"]=str(embedding_api_version)# Catch model_kwargs / kwargs that may contain additional paramsmodel_kwargs=getattr(method_obj,"model_kwargs",None)if(model_kwargsandisinstance(model_kwargs,dict)and_is_fully_serializable(model_kwargs)):fingerprint_data["model_kwargs"]=model_kwargsreturnstable_fingerprint(fingerprint_data)
A directed DAG of artifact identities and their dependency relationships.
Nodes are keyed by identity_key. upstream/downstream are keyed by
identity_key on both sides — provenance artifact_id references are
translated on access.
Source code in packages/episteme-pipeline/episteme_pipeline/artifacts/invalidate.py
classArtifactDependencyGraph:"""A directed DAG of artifact identities and their dependency relationships. Nodes are keyed by ``identity_key``. ``upstream``/``downstream`` are keyed by ``identity_key`` on both sides — provenance ``artifact_id`` references are translated on access. """def__init__(self)->None:self.nodes:dict[str,ArtifactEnvelope]={}self._identity_by_artifact_id:dict[str,str]={}self._raw_upstream:dict[str,tuple[str,...]]={}self._downstream:dict[str,set[str]]=defaultdict(set)self._upstream:dict[str,set[str]]=defaultdict(set)self._unresolved_upstream:dict[str,set[str]]=defaultdict(set)self._edges_resolved=Falsedefadd(self,artifact:ArtifactEnvelope)->None:key=artifact.identity_keyifkeyisNone:returnself.nodes[key]=artifactself._identity_by_artifact_id[artifact.artifact_id]=keyself._raw_upstream[key]=tuple(artifact.provenance.upstream_artifact_ids)self._edges_resolved=Falsedef_resolve_edges(self)->None:"""Translate provenance ``artifact_id`` references into ``identity_key`` edges."""ifself._edges_resolved:returnself._downstream=defaultdict(set)self._upstream=defaultdict(set)self._unresolved_upstream=defaultdict(set)forkey,raw_idsinself._raw_upstream.items():forup_idinraw_ids:up_key=self._identity_by_artifact_id.get(up_id)ifup_keyisNone:# The referenced artifact is not part of this artifact set —# e.g. a phase hydrated from a parent run whose artifacts were# not loaded. Recorded rather than dropped so callers can see# that the graph is incomplete instead of reading a missing# edge as "no dependency".self._unresolved_upstream[key].add(up_id)continueself._downstream[up_key].add(key)self._upstream[key].add(up_key)self._edges_resolved=True@propertydefdownstream(self)->dict[str,set[str]]:"""``{identity_key: set(identity_key)}`` — dependents of each node."""self._resolve_edges()returnself._downstream@propertydefupstream(self)->dict[str,set[str]]:"""``{identity_key: set(identity_key)}`` — dependencies of each node."""self._resolve_edges()returnself._upstream@propertydefunresolved_upstream(self)->dict[str,set[str]]:"""``{identity_key: set(artifact_id)}`` — references to artifacts not in this set."""self._resolve_edges()returnself._unresolved_upstreamdeftopsort(self)->list[str]:"""Kahn's algorithm for topological ordering of the DAG."""downstream=self.downstreamupstream=self.upstreamin_degree:dict[str,int]={nid:0fornidinself.nodes}fornidinself.nodes:fordepinupstream.get(nid,set()):ifdepinin_degree:in_degree[nid]+=1queue:deque[str]=deque(nidfornid,deginin_degree.items()ifdeg==0)order:list[str]=[]whilequeue:nid=queue.popleft()order.append(nid)forchildindownstream.get(nid,set()):in_degree[child]-=1ifin_degree[child]==0:queue.append(child)iflen(order)!=len(self.nodes):raiseValueError("Dependency graph has a cycle")returnorder@classmethoddeffrom_artifacts(cls,artifacts:list[ArtifactEnvelope])->ArtifactDependencyGraph:g=cls()forartinartifacts:g.add(art)returngdefbuild_kind_staleness_map(self,prior_fps:dict[str,str],prior_artifacts:list[ArtifactEnvelope]|None=None,)->dict[str,list[str]]:"""{kind: stale_identity_keys} grouped by ArtifactKind. Useful so upstream callers can map stale deps back to the phase that would need re-execution (each phase produces a fixed set of artifact kinds). """stale_nodes=find_stale_nodes(self,prior_fps,prior_artifacts=prior_artifacts)result:dict[str,list[str]]={}fornidinstale_nodes:art=self.nodes[nid]kind_key=(str(art.kind)ifhasattr(art.kind,"__str__")elsestr(type(art.kind).__name__))result.setdefault(kind_key,[]).append(nid)returnresultdefbuild_phase_staleness_map(self,prior_fps:dict[str,str],prior_artifacts:list[ArtifactEnvelope]|None=None,)->dict[str,list[str]]:"""{phase_name: stale_identity_keys} grouped by ArtifactEnvelop.phase_name. Useful because _choose_reuse_source invalidates by phase_name. """stale_nodes=find_stale_nodes(self,prior_fps,prior_artifacts=prior_artifacts)result:dict[str,list[str]]={}fornidinstale_nodes:art=self.nodes[nid]result.setdefault(art.phase_name,[]).append(nid)returnresult
defbuild_kind_staleness_map(self,prior_fps:dict[str,str],prior_artifacts:list[ArtifactEnvelope]|None=None,)->dict[str,list[str]]:"""{kind: stale_identity_keys} grouped by ArtifactKind. Useful so upstream callers can map stale deps back to the phase that would need re-execution (each phase produces a fixed set of artifact kinds). """stale_nodes=find_stale_nodes(self,prior_fps,prior_artifacts=prior_artifacts)result:dict[str,list[str]]={}fornidinstale_nodes:art=self.nodes[nid]kind_key=(str(art.kind)ifhasattr(art.kind,"__str__")elsestr(type(art.kind).__name__))result.setdefault(kind_key,[]).append(nid)returnresult
{phase_name: stale_identity_keys} grouped by ArtifactEnvelop.phase_name.
Useful because _choose_reuse_source invalidates by phase_name.
Source code in packages/episteme-pipeline/episteme_pipeline/artifacts/invalidate.py
154155156157158159160161162163164165166167168
defbuild_phase_staleness_map(self,prior_fps:dict[str,str],prior_artifacts:list[ArtifactEnvelope]|None=None,)->dict[str,list[str]]:"""{phase_name: stale_identity_keys} grouped by ArtifactEnvelop.phase_name. Useful because _choose_reuse_source invalidates by phase_name. """stale_nodes=find_stale_nodes(self,prior_fps,prior_artifacts=prior_artifacts)result:dict[str,list[str]]={}fornidinstale_nodes:art=self.nodes[nid]result.setdefault(art.phase_name,[]).append(nid)returnresult
deftopsort(self)->list[str]:"""Kahn's algorithm for topological ordering of the DAG."""downstream=self.downstreamupstream=self.upstreamin_degree:dict[str,int]={nid:0fornidinself.nodes}fornidinself.nodes:fordepinupstream.get(nid,set()):ifdepinin_degree:in_degree[nid]+=1queue:deque[str]=deque(nidfornid,deginin_degree.items()ifdeg==0)order:list[str]=[]whilequeue:nid=queue.popleft()order.append(nid)forchildindownstream.get(nid,set()):in_degree[child]-=1ifin_degree[child]==0:queue.append(child)iflen(order)!=len(self.nodes):raiseValueError("Dependency graph has a cycle")returnorder
Return stale node identity keys with structural and fingerprint changes.
A node is stale when:
- It has no entry in prior_fps (new artifact with unknown prior), or
- Its dependency_fingerprint differs from the stored prior value, or
- Its provenance edge set differs from the prior graph (structural diff), or
- It transitively depends on a stale node.
Structural comparison uses prior_upstream when provided (precomputed
{identity_key: upstream_set}), or fallback to prior_artifacts
which are converted via _build_prior_upstream.
Propagates staleness breadth-first through the downstream edges.
Source code in packages/episteme-pipeline/episteme_pipeline/artifacts/invalidate.py
deffind_stale_nodes(dag:ArtifactDependencyGraph,prior_fps:dict[str,str],prior_upstream:dict[str,set[str]]|None=None,prior_artifacts:list[ArtifactEnvelope]|None=None,)->set[str]:"""Return stale node identity keys with structural and fingerprint changes. A node is stale when: - It has no entry in ``prior_fps`` (new artifact with unknown prior), or - Its ``dependency_fingerprint`` differs from the stored prior value, or - Its provenance edge set differs from the prior graph (structural diff), or - It transitively depends on a stale node. Structural comparison uses ``prior_upstream`` when provided (precomputed ``{identity_key: upstream_set}``), or fallback to ``prior_artifacts`` which are converted via ``_build_prior_upstream``. Propagates staleness breadth-first through the downstream edges. """stale:set[str]=set()q:deque[str]=deque()ifprior_upstreamisNoneandprior_artifactsisnotNone:prior_upstream=_build_prior_upstream(prior_artifacts)structurally_stale=_compare_dag_structures(dag,prior_upstreamor{})fornid,artindag.nodes.items():ifart.dependency_fingerprintisNone:continueprior_fp=prior_fps.get(nid)is_structural=nidinstructurally_staleifprior_fpisNoneorart.dependency_fingerprint!=prior_fporis_structural:stale.add(nid)q.append(nid)whileq:nid=q.popleft()forchildinlist(dag.downstream.get(nid,[])):ifchildnotinstale:stale.add(child)q.append(child)returnstale