File size: 6,866 Bytes
551b309
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Network-free contract tests for the AffixIO Hugging Face SDK."""

# Credit: @paparichens

from __future__ import annotations

from typing import Any

import pytest

from affix_huggingface import (
    AdmissionChecks,
    AdmissionDenied,
    AdmissionProof,
    AffixHuggingFace,
    ModelRef,
    StreamNotComplete,
)


class FakeAffixTransport:
    def __init__(self, *, allow: bool = True) -> None:
        self.allow = allow
        self.prove_calls: list[dict[str, Any]] = []
        self.gate_calls: list[dict[str, Any]] = []
        self.attest_calls: list[dict[str, Any]] = []

    def close(self) -> None:
        return None

    def health(self) -> tuple[dict[str, Any], str | None]:
        return {"ok": True}, "req_health"

    def prove(self, **kwargs: Any) -> tuple[dict[str, Any], str | None]:
        self.prove_calls.append(kwargs)
        return {"proof": "proof_hex", "valid": True}, "req_prove"

    def gate(self, **kwargs: Any) -> tuple[dict[str, Any], str | None]:
        self.gate_calls.append(kwargs)
        return (
            {
                "allow": self.allow,
                "reason_code": "ADMITTED" if self.allow else "INVALID_PROOF",
                "receipt_id": "rcpt_1",
                "proof_digest": "abc123",
                "proof_ref": "1:abc123",
                "policy_id": "gate.agent",
                "policy_version": "2026.08",
                "mode": kwargs["mode"],
                "spent": self.allow and kwargs["mode"] == "consume",
                "merkle_root": "root_1",
                "merkle_leaf_hash": "leaf_1",
                "attestation": {"algorithm": "ML-DSA-65"},
            },
            "req_gate",
        )

    def attest(self, payload: dict[str, Any], **kwargs: Any) -> tuple[dict[str, Any], str | None]:
        self.attest_calls.append({"payload": payload, **kwargs})
        return {"attestation": {"algorithm": "ML-DSA-65", "signature": "sig"}}, "req_attest"


class FakeHfClient:
    def __init__(self) -> None:
        self.calls: list[dict[str, Any]] = []

    def chat_completion(
        self,
        messages: list[dict[str, Any]],
        *,
        model: str,
        **kwargs: Any,
    ) -> dict[str, Any] | list[str]:
        self.calls.append(
            {"method": "chat_completion", "messages": messages, "model": model, **kwargs}
        )
        if kwargs.get("stream"):
            return ["token-1", "token-2"]
        return {"id": "hf_response_1", "choices": []}

    def text_generation(self, prompt: str, *, model: str, **kwargs: Any) -> str | list[str]:
        self.calls.append(
            {"method": "text_generation", "prompt": prompt, "model": model, **kwargs}
        )
        if kwargs.get("stream"):
            return ["first", "second"]
        return "generated"

    def feature_extraction(
        self,
        text: str | list[str],
        *,
        model: str,
        **kwargs: Any,
    ) -> list[list[float]]:
        self.calls.append(
            {"method": "feature_extraction", "text": text, "model": model, **kwargs}
        )
        return [[0.1, 0.2]]


def make_client(
    *,
    affix: FakeAffixTransport | None = None,
    hf: FakeHfClient | None = None,
    evidence_mode: str = "required",
) -> tuple[AffixHuggingFace, FakeAffixTransport, FakeHfClient]:
    affix = affix or FakeAffixTransport()
    hf = hf or FakeHfClient()
    client = AffixHuggingFace(
        affix_transport=affix,  # type: ignore[arg-type]
        hf_client=hf,
        evidence_mode=evidence_mode,  # type: ignore[arg-type]
    )
    return client, affix, hf


def test_model_binding_is_deterministic_and_excludes_content() -> None:
    model = ModelRef(
        model_id="org/model",
        revision="abc",
        provider="hf-inference",
    )
    assert len(model.binding_digest) == 64
    assert model.binding_digest == ModelRef(
        model_id="org/model",
        revision="abc",
        provider="hf-inference",
    ).binding_digest
    assert "prompt" not in model.binding()


def test_denial_happens_before_hugging_face_call() -> None:
    client, _, hf = make_client(affix=FakeAffixTransport(allow=False))
    with pytest.raises(AdmissionDenied) as exc:
        client.chat_completion(
            [{"role": "user", "content": "private prompt"}],
            model=ModelRef("org/model"),
            proof=AdmissionProof("bad-proof"),
        )
    assert exc.value.reason_code == "INVALID_PROOF"
    assert hf.calls == []


def test_authorised_chat_returns_output_and_evidence() -> None:
    client, affix, hf = make_client()
    result = client.chat_completion(
        [{"role": "user", "content": "private prompt"}],
        model=ModelRef("org/model", revision="commit-sha"),
        proof=AdmissionProof("proof_hex"),
        max_tokens=20,
    )

    assert result.output["id"] == "hf_response_1"
    assert result.receipt.gate.allow is True
    assert result.receipt.completion is not None
    assert hf.calls[0]["messages"][0]["content"] == "private prompt"
    assert "private prompt" not in repr(affix.gate_calls)
    assert "private prompt" not in repr(affix.attest_calls)
    assert affix.attest_calls[0]["payload"]["prompt_included"] is False
    assert affix.attest_calls[0]["payload"]["output_included"] is False


def test_checks_use_remote_prove_then_consume() -> None:
    client, affix, _ = make_client(evidence_mode="off")
    client.text_generation(
        "private input",
        model=ModelRef("org/model"),
        checks=AdmissionChecks(
            entitled=True,
            data_route_allowed=True,
            controls_satisfied=True,
        ),
    )
    assert affix.prove_calls[0]["fields"] == {
        "condition_greater1": True,
        "condition_greater2": True,
        "condition_greater3": True,
    }
    assert affix.gate_calls[0]["mode"] == "consume"
    assert "private input" not in repr(affix.prove_calls)
    assert "private input" not in repr(affix.gate_calls)


def test_stream_attests_only_after_consumption() -> None:
    client, affix, _ = make_client()
    stream = client.stream_text_generation(
        "private input",
        model=ModelRef("org/model"),
        proof=AdmissionProof("proof_hex"),
    )
    with pytest.raises(StreamNotComplete):
        _ = stream.final_receipt
    assert affix.attest_calls == []
    assert list(stream) == ["first", "second"]
    assert stream.complete is True
    assert stream.final_receipt.completion is not None
    assert len(affix.attest_calls) == 1


def test_inspect_does_not_call_hugging_face() -> None:
    client, affix, hf = make_client(evidence_mode="off")
    receipt = client.inspect(
        ModelRef("org/model"),
        proof=AdmissionProof("proof_hex"),
    )
    assert receipt.allow is True
    assert receipt.mode == "check"
    assert affix.gate_calls[0]["mode"] == "check"
    assert hf.calls == []