Skip to content

Core Protocols & Fingerprinting Reference

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.

Phase Runner Protocol

PhaseRunner

Abstract base for all pipeline phases.

Bases: 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.

Source code in packages/episteme-pipeline/episteme_pipeline/protocols/phase_runner.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class PhaseRunner[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

    @abstractmethod
    async def run(self, input: InputT, context: ArtifactExecutionContext) -> ArtifactCollection: ...

    def components(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.
        """
        from episteme_pipeline.protocols.fingerprint import find_components

        return find_components(self)

components()

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.

Source code in packages/episteme-pipeline/episteme_pipeline/protocols/phase_runner.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def components(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.
    """
    from episteme_pipeline.protocols.fingerprint import find_components

    return find_components(self)

PhaseRunner.components()

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.

Returns

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def components(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.
    """
    from episteme_pipeline.protocols.fingerprint import find_components

    return find_components(self)

Component Fingerprinting & Discovery

Fingerprintable

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@runtime_checkable
class Fingerprintable(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.
    """

    def fingerprint(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.
        """
        ...

fingerprint()

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.

Source code in packages/episteme-pipeline/episteme_pipeline/protocols/fingerprint.py
57
58
59
60
61
62
63
64
65
66
def fingerprint(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.
    """
    ...

find_components

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().

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.

Source code in packages/episteme-pipeline/episteme_pipeline/protocols/fingerprint.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def find_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.
    """
    if visited is None:
        visited = set()

    if root is None or id(root) in visited:
        return {}

    if isinstance(root, (_PRIMITIVE_TYPES, list, tuple, set, dict, NonCallableMock)):
        return {}

    visited.add(id(root))
    discovered: dict[str, Any] = {}

    # Extract instance attributes
    raw_dict = getattr(root, "__dict__", None)
    if not isinstance(raw_dict, dict):
        return {}

    attrs = {k: v for k, v in raw_dict.items() if isinstance(k, str) and not k.startswith("_")}

    for name, value in attrs.items():
        if value is None:
            continue

        full_path = f"{prefix}.{name}" if prefix else name

        if is_component(value, attr_name=name):
            discovered[full_path] = value

        if not isinstance(value, (list, tuple, dict)):
            discovered.update(find_components(value, prefix=full_path, visited=visited))
        elif isinstance(value, (list, tuple)):
            for i, item in enumerate(value):
                sub_path = f"{full_path}[{i}]"
                if is_component(item):
                    discovered[sub_path] = item
                discovered.update(find_components(item, prefix=sub_path, visited=visited))
        elif isinstance(value, dict):
            for k, item in value.items():
                if isinstance(k, str) and not k.startswith("_"):
                    sub_path = f"{full_path}.{k}"
                    if is_component(item):
                        discovered[sub_path] = item
                    discovered.update(find_components(item, prefix=sub_path, visited=visited))

    return discovered

is_component

Predicate used by find_components to decide whether an attribute qualifies as a fingerprintable component.

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.

Source code in packages/episteme-pipeline/episteme_pipeline/protocols/fingerprint.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def is_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.
    """
    if val is None or isinstance(val, _PRIMITIVE_TYPES):
        return False

    # Explicit protocol conformance (structural typing)
    if isinstance(val, Fingerprintable) and callable(getattr(val, "fingerprint", None)):
        return True

    # Pydantic models (configs, schemas, data contracts) are fingerprinted separately
    if isinstance(val, BaseModel):
        return False

    # Core runner component attributes (backwards compatibility for test doubles)
    return attr_name in _CORE_COMPONENT_NAMES

Run Fingerprint Functions

Deterministic SHA-256 hashing primitives generated by pipeline/runs/fingerprints.py and used to build the run manifest fingerprints for pre-execution phase reuse.

stable_fingerprint

Source code in packages/episteme-pipeline/episteme_pipeline/runs/fingerprints.py
14
15
16
17
18
def stable_fingerprint(value: Any) -> str:
    payload = json.dumps(
        value, sort_keys=True, separators=(",", ":"), ensure_ascii=False
    )
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()

fingerprint_existing_sources

Source code in packages/episteme-pipeline/episteme_pipeline/runs/fingerprints.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def fingerprint_existing_sources(
    source_paths: list[str], bib_paths: list[str] | None = None
) -> str:
    records: list[dict[str, Any]] = []
    all_paths = [("source", p) for p in sorted(source_paths)]
    if bib_paths:
        all_paths.extend(("bib", p) for p in sorted(bib_paths))

    for kind, source_path in all_paths:
        path = Path(source_path)
        if path.exists():
            stat = path.stat()
            try:
                content_hash = hashlib.sha256(path.read_bytes()).hexdigest()
            except (OSError, PermissionError):
                content_hash = None
            records.append(
                {
                    "kind": kind,
                    "path": source_path,
                    "size": stat.st_size,
                    "content_hash": content_hash,
                }
            )
        else:
            records.append({"kind": kind, "path": source_path, "missing": True})
    return stable_fingerprint(records)

fingerprint_structural_anchor

Compute a deterministic SHA-256 fingerprint for a GlobalStructuralAnchor.

Parameters

anchor : GlobalStructuralAnchor | None Target structural anchor instance to hash.

Returns

str | None Deterministic hexadecimal SHA-256 fingerprint string, or None if anchor is None.

Source code in packages/episteme-pipeline/episteme_pipeline/runs/fingerprints.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def fingerprint_structural_anchor(anchor: Any | None) -> str | None:
    """
    Compute a deterministic SHA-256 fingerprint for a GlobalStructuralAnchor.

    Parameters
    ----------
    anchor : GlobalStructuralAnchor | None
        Target structural anchor instance to hash.

    Returns
    -------
    str | None
        Deterministic hexadecimal SHA-256 fingerprint string, or None if anchor is None.
    """
    if anchor is None:
        return None

    dumped = (
        anchor.model_dump(mode="json")
        if hasattr(anchor, "model_dump")
        else getattr(anchor, "__dict__", str(anchor))
    )
    return stable_fingerprint(dumped)

fingerprint_phase_config

Source code in packages/episteme-pipeline/episteme_pipeline/runs/fingerprints.py
37
38
39
40
41
42
43
44
45
46
47
48
49
def fingerprint_phase_config(config: Any) -> str:
    if hasattr(config, "model_dump"):
        return stable_fingerprint(config.model_dump(mode="json"))
    phase_dict = getattr(config, "__dict__", None)
    if isinstance(phase_dict, dict):
        serializable = {
            key: value
            for key, value in phase_dict.items()
            if _is_fully_serializable(value)
        }
        if serializable:
            return stable_fingerprint(serializable)
    return stable_fingerprint({"class": config.__class__.__name__})

fingerprint_phase_config_nested

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def fingerprint_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".
    """
    if hasattr(config, "model_dump"):
        dumped = config.model_dump(mode="json")
    else:
        dumped: dict[str, Any] = {}
        phase_dict = getattr(config, "__dict__", None)
        if isinstance(phase_dict, dict):
            for key, value in phase_dict.items():
                if hasattr(value, "model_dump"):
                    dumped[key] = value.model_dump(mode="json")
                elif _is_fully_serializable(value):
                    dumped[key] = value

    return _fingerprint_nested_leafs(dumped, prefix="")

fingerprint_method

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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def fingerprint_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.
    """
    if method_obj is None:
        return None

    explicit = getattr(method_obj, "fingerprint", None)
    if callable(explicit):
        try:
            value = explicit()
            if _is_fully_serializable(value):
                return stable_fingerprint(
                    {"class": method_obj.__class__.__name__, "fingerprint": value}
                )
        except Exception as ex:
            logger.exception(ex)

    fingerprint_data: dict[str, Any] = {"class": method_obj.__class__.__name__}
    model_name = getattr(method_obj, "model_name", None)
    if model_name:
        fingerprint_data["model"] = str(model_name)
    model_name_or_provider = getattr(method_obj, "model_name_or_provider", None)
    if model_name_or_provider:
        fingerprint_data["model_provider"] = str(model_name_or_provider)
    model = getattr(method_obj, "model", None)
    if model is not None:
        fingerprint_data["model_ref"] = str(model)

    # API version detection — important for LLM API changes
    api_version = getattr(method_obj, "api_version", None)
    if api_version is not None and _is_fully_serializable(api_version):
        fingerprint_data["api_version"] = str(api_version)

    # Provider/endpoint configuration
    base_url = getattr(method_obj, "base_url", None)
    if base_url is not None and _is_fully_serializable(base_url):
        fingerprint_data["base_url"] = str(base_url)

    # Runtime parameters that affect model output
    temperature = getattr(method_obj, "temperature", None)
    if temperature is not None and _is_fully_serializable(temperature):
        fingerprint_data["temperature"] = temperature

    max_tokens = getattr(method_obj, "max_tokens", None)
    if max_tokens is not None and _is_fully_serializable(max_tokens):
        fingerprint_data["max_tokens"] = max_tokens

    top_p = getattr(method_obj, "top_p", None)
    if top_p is not None and _is_fully_serializable(top_p):
        fingerprint_data["top_p"] = top_p

    n = getattr(method_obj, "n", None)
    if n is not None and _is_fully_serializable(n):
        fingerprint_data["n"] = n

    # Embedding-specific parameters
    dimensions = getattr(method_obj, "dimensions", None)
    if dimensions is not None and _is_fully_serializable(dimensions):
        fingerprint_data["dimensions"] = dimensions

    embedding_api_version = getattr(method_obj, "embedding_api_version", None)
    if embedding_api_version is not None and _is_fully_serializable(
        embedding_api_version
    ):
        fingerprint_data["embedding_api_version"] = str(embedding_api_version)

    # Catch model_kwargs / kwargs that may contain additional params
    model_kwargs = getattr(method_obj, "model_kwargs", None)
    if (
        model_kwargs
        and isinstance(model_kwargs, dict)
        and _is_fully_serializable(model_kwargs)
    ):
        fingerprint_data["model_kwargs"] = model_kwargs

    return stable_fingerprint(fingerprint_data)

Artifact Dependency Graph

Fine-grained cross-run staleness detection over persisted artifacts, located in pipeline/artifacts/invalidate.py.

ArtifactDependencyGraph

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
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
class ArtifactDependencyGraph:
    """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 = False

    def add(self, artifact: ArtifactEnvelope) -> None:
        key = artifact.identity_key
        if key is None:
            return
        self.nodes[key] = artifact
        self._identity_by_artifact_id[artifact.artifact_id] = key
        self._raw_upstream[key] = tuple(artifact.provenance.upstream_artifact_ids)
        self._edges_resolved = False

    def _resolve_edges(self) -> None:
        """Translate provenance ``artifact_id`` references into ``identity_key`` edges."""
        if self._edges_resolved:
            return
        self._downstream = defaultdict(set)
        self._upstream = defaultdict(set)
        self._unresolved_upstream = defaultdict(set)
        for key, raw_ids in self._raw_upstream.items():
            for up_id in raw_ids:
                up_key = self._identity_by_artifact_id.get(up_id)
                if up_key is None:
                    # 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)
                    continue
                self._downstream[up_key].add(key)
                self._upstream[key].add(up_key)
        self._edges_resolved = True

    @property
    def downstream(self) -> dict[str, set[str]]:
        """``{identity_key: set(identity_key)}`` — dependents of each node."""
        self._resolve_edges()
        return self._downstream

    @property
    def upstream(self) -> dict[str, set[str]]:
        """``{identity_key: set(identity_key)}`` — dependencies of each node."""
        self._resolve_edges()
        return self._upstream

    @property
    def unresolved_upstream(self) -> dict[str, set[str]]:
        """``{identity_key: set(artifact_id)}`` — references to artifacts not in this set."""
        self._resolve_edges()
        return self._unresolved_upstream

    def topsort(self) -> list[str]:
        """Kahn's algorithm for topological ordering of the DAG."""
        downstream = self.downstream
        upstream = self.upstream
        in_degree: dict[str, int] = {nid: 0 for nid in self.nodes}
        for nid in self.nodes:
            for dep in upstream.get(nid, set()):
                if dep in in_degree:
                    in_degree[nid] += 1
        queue: deque[str] = deque(nid for nid, deg in in_degree.items() if deg == 0)
        order: list[str] = []
        while queue:
            nid = queue.popleft()
            order.append(nid)
            for child in downstream.get(nid, set()):
                in_degree[child] -= 1
                if in_degree[child] == 0:
                    queue.append(child)
        if len(order) != len(self.nodes):
            raise ValueError("Dependency graph has a cycle")
        return order

    @classmethod
    def from_artifacts(
        cls, artifacts: list[ArtifactEnvelope]
    ) -> ArtifactDependencyGraph:
        g = cls()
        for art in artifacts:
            g.add(art)
        return g

    def build_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]] = {}
        for nid in stale_nodes:
            art = self.nodes[nid]
            kind_key = (
                str(art.kind)
                if hasattr(art.kind, "__str__")
                else str(type(art.kind).__name__)
            )
            result.setdefault(kind_key, []).append(nid)
        return result

    def build_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]] = {}
        for nid in stale_nodes:
            art = self.nodes[nid]
            result.setdefault(art.phase_name, []).append(nid)
        return result

downstream property

{identity_key: set(identity_key)} — dependents of each node.

unresolved_upstream property

{identity_key: set(artifact_id)} — references to artifacts not in this set.

upstream property

{identity_key: set(identity_key)} — dependencies of each node.

build_kind_staleness_map(prior_fps, prior_artifacts=None)

{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).

Source code in packages/episteme-pipeline/episteme_pipeline/artifacts/invalidate.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def build_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]] = {}
    for nid in stale_nodes:
        art = self.nodes[nid]
        kind_key = (
            str(art.kind)
            if hasattr(art.kind, "__str__")
            else str(type(art.kind).__name__)
        )
        result.setdefault(kind_key, []).append(nid)
    return result

build_phase_staleness_map(prior_fps, prior_artifacts=None)

{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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def build_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]] = {}
    for nid in stale_nodes:
        art = self.nodes[nid]
        result.setdefault(art.phase_name, []).append(nid)
    return result

topsort()

Kahn's algorithm for topological ordering of the DAG.

Source code in packages/episteme-pipeline/episteme_pipeline/artifacts/invalidate.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def topsort(self) -> list[str]:
    """Kahn's algorithm for topological ordering of the DAG."""
    downstream = self.downstream
    upstream = self.upstream
    in_degree: dict[str, int] = {nid: 0 for nid in self.nodes}
    for nid in self.nodes:
        for dep in upstream.get(nid, set()):
            if dep in in_degree:
                in_degree[nid] += 1
    queue: deque[str] = deque(nid for nid, deg in in_degree.items() if deg == 0)
    order: list[str] = []
    while queue:
        nid = queue.popleft()
        order.append(nid)
        for child in downstream.get(nid, set()):
            in_degree[child] -= 1
            if in_degree[child] == 0:
                queue.append(child)
    if len(order) != len(self.nodes):
        raise ValueError("Dependency graph has a cycle")
    return order

find_stale_nodes

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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def find_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()

    if prior_upstream is None and prior_artifacts is not None:
        prior_upstream = _build_prior_upstream(prior_artifacts)

    structurally_stale = _compare_dag_structures(dag, prior_upstream or {})

    for nid, art in dag.nodes.items():
        if art.dependency_fingerprint is None:
            continue
        prior_fp = prior_fps.get(nid)
        is_structural = nid in structurally_stale
        if prior_fp is None or art.dependency_fingerprint != prior_fp or is_structural:
            stale.add(nid)
            q.append(nid)

    while q:
        nid = q.popleft()
        for child in list(dag.downstream.get(nid, [])):
            if child not in stale:
                stale.add(child)
                q.append(child)

    return stale

build_prior_fingerprints

Extract {identity_key: dependency_fingerprint} map from artifacts.

Source code in packages/episteme-pipeline/episteme_pipeline/artifacts/invalidate.py
259
260
261
262
263
264
265
266
267
def build_prior_fingerprints(
    artifacts: list[ArtifactEnvelope],
) -> dict[str, str]:
    """Extract {identity_key: dependency_fingerprint} map from artifacts."""
    fps: dict[str, str] = {}
    for art in artifacts:
        if art.identity_key and art.dependency_fingerprint:
            fps[art.identity_key] = art.dependency_fingerprint
    return fps