File size: 12,228 Bytes
58c2da3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
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
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
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
195
196
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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""Single ordered orchestration shell for the completed blind dataset stages."""

from __future__ import annotations

from typing import Any, Protocol

from pydantic import BaseModel

from gcmd_classifier.datasets.errors import DatasetOrchestrationError
from gcmd_classifier.datasets.models import (
    DatasetClassificationOutcome,
    DatasetEvidencePacket,
    ResolvedCMRCollection,
)
from gcmd_classifier.datasets.orchestration import DatasetRunController, DurableInferenceClient
from gcmd_classifier.datasets.runtime_models import (
    ArtifactReference,
    ArtifactType,
    BlindPipelineTerminal,
    CheckpointStatus,
    DatasetRuntimeFailure,
    PersistedExpertSourceBoundary,
    PipelineStage,
    TerminalOutcome,
)
from gcmd_classifier.datasets.runtime_persistence import (
    DatasetArtifactStore,
    canonical_json_bytes,
    persist_expert_source_boundary,
    verify_persisted_blind_result,
)
from gcmd_classifier.llm.base import ModelClient


class BlindStageServices(Protocol):
    """Adapters call the already implemented stage functions; they add no stage logic."""

    def execute(
        self,
        stage: PipelineStage,
        context: dict[PipelineStage, Any],
        model_client: ModelClient,
    ) -> Any:
        """Execute one named stage and return its existing typed stage result."""


_ORDER = (
    PipelineStage.CMR_SOURCE,
    PipelineStage.IDENTITY,
    PipelineStage.BLIND_BOUNDARY,
    PipelineStage.README_DISCOVERY,
    PipelineStage.README_SELECTION,
    PipelineStage.README_RETRIEVAL,
    PipelineStage.SOURCE_PERSISTENCE,
    PipelineStage.EXTRACTION,
    PipelineStage.PRODUCT_RESOLUTION,
    PipelineStage.EVIDENCE_SELECTION,
    PipelineStage.EVIDENCE_PACKET,
    PipelineStage.CLASSIFICATION,
)

_ARTIFACT_TYPE = {
    PipelineStage.CMR_SOURCE: ArtifactType.CMR_RESPONSE,
    PipelineStage.IDENTITY: ArtifactType.COLLECTION_SNAPSHOT,
    PipelineStage.BLIND_BOUNDARY: ArtifactType.COLLECTION_SNAPSHOT,
    PipelineStage.README_DISCOVERY: ArtifactType.README_METADATA,
    PipelineStage.README_SELECTION: ArtifactType.README_METADATA,
    PipelineStage.README_RETRIEVAL: ArtifactType.README_PDF,
    PipelineStage.SOURCE_PERSISTENCE: ArtifactType.README_METADATA,
    PipelineStage.EXTRACTION: ArtifactType.EXTRACTION_MANIFEST,
    PipelineStage.PRODUCT_RESOLUTION: ArtifactType.PRODUCT_RESOLUTION,
    PipelineStage.EVIDENCE_SELECTION: ArtifactType.EVIDENCE_SELECTION,
    PipelineStage.EVIDENCE_PACKET: ArtifactType.EVIDENCE_PACKET,
    PipelineStage.CLASSIFICATION: ArtifactType.BLIND_RESULT,
}


class BlindDatasetPipeline:
    """Execute the approved blind order with durable state and artifact boundaries."""

    def __init__(
        self,
        *,
        controller: DatasetRunController,
        store: DatasetArtifactStore,
        services: BlindStageServices,
        model_client: ModelClient,
        vocabulary_hash: str,
    ) -> None:
        self.controller = controller
        self.store = store
        self.services = services
        self.model_client = DurableInferenceClient(model_client, controller)
        self.vocabulary_hash = vocabulary_hash
        self._source_boundary: PersistedExpertSourceBoundary | None = None

    def run(self) -> BlindPipelineTerminal:
        context: dict[PipelineStage, Any] = {}
        references: dict[PipelineStage, ArtifactReference] = {}
        try:
            for stage in _ORDER:
                self.controller.begin(stage, f"Begin {stage.value}.")
                value = self.services.execute(stage, context, self.model_client)
                if stage is PipelineStage.IDENTITY:
                    if not isinstance(value, ResolvedCMRCollection):
                        raise DatasetOrchestrationError(
                            "EXPERT_SOURCE_BINDING_MISSING",
                            "Identity stage must return the resolved CMR collection.",
                        )
                    self._source_boundary = persist_expert_source_boundary(
                        store=self.store,
                        run=self.controller.state.run,
                        session_id=self.controller.state.session.session_id,
                        collection=value,
                        cmr_source_artifact=references[PipelineStage.CMR_SOURCE],
                    )
                    context.clear()
                    context[PipelineStage.CMR_SOURCE] = references[PipelineStage.CMR_SOURCE]
                    value = self._source_boundary.blind_view
                if stage is PipelineStage.README_DISCOVERY and value is None:
                    self.controller.transition(
                        stage, CheckpointStatus.SKIPPED, "No README candidate was discovered."
                    )
                    return self._terminal(TerminalOutcome.COMPLETED_SKIPPED)
                if stage is PipelineStage.SOURCE_PERSISTENCE:
                    # The stage exists as an explicit service checkpoint; exact source bytes
                    # were already published at their acquisition boundaries.
                    reference = references[PipelineStage.README_RETRIEVAL]
                else:
                    reference = self._persist(stage, value, context)
                references[stage] = reference
                context[stage] = value
                checkpoint_artifacts = (reference,)
                if stage is PipelineStage.IDENTITY and self._source_boundary is not None:
                    checkpoint_artifacts = (
                        reference,
                        self._source_boundary.cmr_source_artifact,
                        self._source_boundary.sealed_expert_artifact,
                        self._source_boundary.expert_source_binding_artifact,
                    )
                self.controller.complete(
                    stage, f"Completed {stage.value}.", artifacts=checkpoint_artifacts
                )
                if stage is PipelineStage.CLASSIFICATION:
                    self.controller.mark_blind_result(produced=True)
                    self.controller.begin(
                        PipelineStage.BLIND_RESULT_PERSISTENCE,
                        "Persist blind result.",
                    )
                    self.controller.complete(
                        PipelineStage.BLIND_RESULT_PERSISTENCE,
                        "Blind result atomically persisted.",
                        artifacts=(reference,),
                    )
                    self.controller.mark_blind_result(persisted=True)
            result = context[PipelineStage.CLASSIFICATION]
            packet = self._packet(context[PipelineStage.EVIDENCE_PACKET])
            verified = verify_persisted_blind_result(
                store=self.store,
                run=self.controller.state.run,
                session_id=self.controller.state.session.session_id,
                reference=references[PipelineStage.CLASSIFICATION],
                expected_packet_sha256=packet.packet_sha256,
                expected_native_id=result.identity.native_id,
                vocabulary_hash=self.vocabulary_hash,
                source_boundary=self._required_source_boundary(),
            )
            self.controller.begin(
                PipelineStage.BLIND_RESULT_VERIFICATION, "Verify persisted blind result."
            )
            self.controller.complete(
                PipelineStage.BLIND_RESULT_VERIFICATION,
                "Persisted blind-result hash verified.",
                artifacts=(verified.artifact,),
            )
            self.controller.mark_blind_result(verified=True)
            terminal = (
                TerminalOutcome.COMPLETED_NOT_CLASSIFIED
                if result.classification_outcome is DatasetClassificationOutcome.NOT_CLASSIFIED
                else TerminalOutcome.COMPLETED_CLASSIFIED
            )
            return self._terminal(terminal, verified=verified)
        except Exception as exc:
            attempted = self.controller.state.classification_attempted
            failure = DatasetRuntimeFailure(
                code=getattr(exc, "code", "BLIND_PIPELINE_FAILED"),
                stage=self.controller.state.checkpoints[-1].stage,
                message="Blind dataset pipeline stage failed.",
                retryable=False,
                classification_attempted=attempted,
            )
            return self._terminal(
                TerminalOutcome.POST_INFERENCE_FAILURE
                if attempted
                else TerminalOutcome.PRE_INFERENCE_FAILURE,
                failure=failure,
            )

    def _required_source_boundary(self) -> PersistedExpertSourceBoundary:
        if self._source_boundary is None:
            raise DatasetOrchestrationError(
                "COMPARISON_PROVENANCE_INCOMPLETE",
                "Verified blind results require persisted expert source provenance.",
            )
        return self._source_boundary

    def _persist(
        self, stage: PipelineStage, value: Any, context: dict[PipelineStage, Any]
    ) -> ArtifactReference:
        if stage is PipelineStage.CMR_SOURCE and hasattr(value, "response_bytes"):
            data = value.response_bytes
        elif stage is PipelineStage.README_RETRIEVAL and hasattr(value, "content"):
            data = value.content
        elif isinstance(value, bytes):
            data = value
        elif isinstance(value, BaseModel):
            data = canonical_json_bytes(value)
        elif isinstance(value, dict):
            data = canonical_json_bytes(value)
        else:
            raise DatasetOrchestrationError(
                "UNPERSISTABLE_STAGE_RESULT", "Stage did not return a typed persistable value."
            )
        if stage not in {PipelineStage.CMR_SOURCE} and b'"ScienceKeywords"' in data:
            raise DatasetOrchestrationError(
                "BLIND_BOUNDARY_VIOLATION", "Expert keywords entered a blind artifact."
            )
        upstream = tuple(reference.sha256 for reference in self._upstream_references(context))
        name = (
            "blind_result.json"
            if stage is PipelineStage.CLASSIFICATION
            else f"artifacts/{stage.value}.json"
        )
        if stage is PipelineStage.README_RETRIEVAL:
            name = "selected_readme.pdf"
        return self.store.persist_bytes(
            run=self.controller.state.run,
            session_id=self.controller.state.session.session_id,
            relative_name=name,
            data=data,
            artifact_type=_ARTIFACT_TYPE[stage],
            upstream_sha256=upstream,
        )

    def _upstream_references(
        self, context: dict[PipelineStage, Any]
    ) -> tuple[ArtifactReference, ...]:
        refs: list[ArtifactReference] = []
        for checkpoint in self.controller.state.checkpoints:
            if checkpoint.status is CheckpointStatus.COMPLETED:
                refs.extend(checkpoint.artifact_references)
        return tuple(refs)

    @staticmethod
    def _packet(value: Any) -> DatasetEvidencePacket:
        if isinstance(value, DatasetEvidencePacket):
            return value
        packet = getattr(value, "packet", None)
        if isinstance(packet, DatasetEvidencePacket):
            return packet
        raise DatasetOrchestrationError(
            "PACKET_RESULT_INVALID", "Evidence packet stage returned no typed packet."
        )

    def _terminal(
        self,
        outcome: TerminalOutcome,
        *,
        verified: Any = None,
        failure: DatasetRuntimeFailure | None = None,
    ) -> BlindPipelineTerminal:
        status = (
            CheckpointStatus.SKIPPED
            if outcome is TerminalOutcome.COMPLETED_SKIPPED
            else CheckpointStatus.FAILED
            if failure is not None
            else CheckpointStatus.COMPLETED
        )
        self.controller.transition(
            PipelineStage.TERMINAL,
            status,
            f"Terminal outcome: {outcome.value}.",
            terminal_outcome=outcome,
        )
        return BlindPipelineTerminal(
            state=self.controller.state,
            terminal_outcome=outcome,
            verified_blind_result=verified,
            failure=failure,
        )