File size: 12,368 Bytes
a9e27c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
"""What the model fallback sequence does after each kind of candidate failure."""

from collections.abc import AsyncIterator
from dataclasses import dataclass, field

import httpx2
import pytest
from loguru import logger

from free_claude_code.application.model_fallback import stream_model_candidates
from free_claude_code.application.routing import (
    ProviderModelCandidate,
    ProviderModelTarget,
)
from free_claude_code.core.failures import ExecutionFailure, FailureKind
from free_claude_code.core.stream_delivery import (
    StreamDeliveryState,
    bind_stream_delivery,
)
from free_claude_code.core.stream_output import StreamOutput
from free_claude_code.core.stream_recovery import (
    ContinuationSeed,
    DeliveredPrefix,
    SourceRecoverySnapshot,
    StreamFailureContext,
)
from tests.providers.test_lmstudio import (
    make_request,
    metadata_response,
    provider_with_http,
)

NO_CONTEXT = None
CLEAN = SourceRecoverySnapshot()


def _failure(
    context: SourceRecoverySnapshot | None,
    *,
    status: int = 502,
    retryable: bool = True,
) -> ExecutionFailure:
    return ExecutionFailure(
        kind=FailureKind.UPSTREAM,
        status_code=status,
        message=f"failed with {status}",
        retryable=retryable,
        stream_context=StreamFailureContext(context) if context is not None else None,
    )


@dataclass(frozen=True)
class Candidate:
    """One scripted candidate: frames it yields, then how it ends."""

    frames: tuple[str, ...] = ()
    release: bool = False
    failure: ExecutionFailure | None = None
    at_open: bool = False


def ok(*frames: str) -> Candidate:
    return Candidate(frames=frames or ("ok",), release=True)


def open_fails(failure: ExecutionFailure) -> Candidate:
    return Candidate(failure=failure, at_open=True)


def fails_after(
    *frames: str, failure: ExecutionFailure, release: bool = True
) -> Candidate:
    return Candidate(frames=frames, release=release, failure=failure)


@dataclass
class Outcome:
    opened: list[tuple[int, str | None]] = field(default_factory=list)
    frames: list[str] = field(default_factory=list)
    raised: int | None = None
    transition: str | None = None
    fallbacks: list[tuple[str, str | None]] = field(default_factory=list)
    selected: list[int] = field(default_factory=list)


async def _run(
    *script: Candidate, prefix_calls: bool = False, reads: list[str] | None = None
) -> Outcome:
    state = StreamDeliveryState()
    delivered: list[str] = []

    def prefix() -> DeliveredPrefix:
        text = "".join(delivered)
        if reads is not None:
            reads.append(text)
        return DeliveredPrefix(
            text=text,
            thinking="",
            has_calls=prefix_calls,
            eligible=True,
            can_handoff=True,
            unsafe_reason=None,
            continuation=ContinuationSeed(
                "messages", ({"type": "text", "text": text},)
            ),
        )

    state.bind_prefix(prefix)
    outcome = Outcome()

    async def body(candidate: Candidate) -> AsyncIterator[StreamOutput]:
        for frame in candidate.frames:
            yield StreamOutput((frame,))
            if candidate.release:
                delivered.append(frame)
                state.release_content()
        if candidate.failure is not None:
            raise candidate.failure

    async def open_candidate(
        index: int,
        _candidate: ProviderModelCandidate,
        continuation: ContinuationSeed | None,
    ) -> AsyncIterator[StreamOutput]:
        outcome.opened.append(
            (index, continuation.readable_text("text") if continuation else None)
        )
        candidate = script[index]
        if candidate.at_open:
            assert candidate.failure is not None
            raise candidate.failure
        return body(candidate)

    candidates = tuple(
        ProviderModelCandidate(ProviderModelTarget("p", f"m{i}", f"p/m{i}"))
        for i in range(len(script))
    )

    def sink(message) -> None:
        payload = message.record["extra"].get("trace_payload")
        if payload is None:
            return
        if payload["event"] == "free_claude_code.model_fallback.started":
            outcome.fallbacks.append(
                (payload["recovery_action"], payload["recovery_reason"])
            )
        elif payload["event"] == "free_claude_code.model_fallback.selected":
            outcome.selected.append(payload["candidate_index"])

    sink_id = logger.add(sink, level="DEBUG")
    try:
        async for chunk in stream_model_candidates(
            candidates,
            open_candidate,
            get_delivery=lambda: state,
            request_id="decisions",
            wire_api="messages",
        ):
            outcome.frames.extend(chunk.frames)
    except ExecutionFailure as failure:
        outcome.raised = failure.status_code
    finally:
        logger.remove(sink_id)
    outcome.transition = state.transition
    return outcome


@pytest.mark.asyncio
async def test_first_candidate_success_never_falls_back():
    outcome = await _run(ok("a"), ok("b"))

    assert outcome == Outcome(opened=[(0, None)], frames=["a"])


@pytest.mark.asyncio
@pytest.mark.parametrize("retryable", [True, False])
async def test_failure_without_context_before_any_delivery_restarts(retryable):
    outcome = await _run(
        open_fails(_failure(NO_CONTEXT, status=400, retryable=retryable)), ok("b")
    )

    assert outcome == Outcome(
        opened=[(0, None), (1, None)],
        frames=["b"],
        fallbacks=[("restart", "no_candidate_output")],
        selected=[2],
    )


@pytest.mark.asyncio
async def test_hidden_output_restarts_from_scratch():
    outcome = await _run(
        fails_after("a", failure=_failure(CLEAN), release=False), ok("b")
    )

    assert outcome == Outcome(
        opened=[(0, None), (1, None)],
        frames=["a", "b"],
        fallbacks=[("restart", "no_delivered_content")],
        selected=[2],
    )


@pytest.mark.asyncio
async def test_released_output_continues_from_the_delivered_prefix():
    outcome = await _run(fails_after("a", failure=_failure(CLEAN)), ok("b"))

    assert outcome == Outcome(
        opened=[(0, None), (1, "a")],
        frames=["a", "b"],
        transition="continue",
        fallbacks=[("continue", "portable_prefix")],
        selected=[2],
    )


@pytest.mark.asyncio
async def test_each_continuation_carries_the_latest_prefix():
    outcome = await _run(
        fails_after("a", failure=_failure(CLEAN)),
        fails_after("b", failure=_failure(CLEAN)),
        ok("c"),
    )

    assert outcome.opened == [(0, None), (1, "a"), (2, "ab")]
    assert outcome.frames == ["a", "b", "c"]
    assert outcome.fallbacks == [("continue", "portable_prefix")] * 2


@pytest.mark.asyncio
async def test_released_tool_calls_hand_off_instead_of_falling_back():
    outcome = await _run(
        fails_after("a", failure=_failure(CLEAN)), ok("b"), prefix_calls=True
    )

    assert outcome == Outcome(opened=[(0, None)], frames=["a"], transition="handoff")


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("source", "release"),
    [
        pytest.param(
            SourceRecoverySnapshot(normal_stop_seen=True), True, id="normal_stop"
        ),
        pytest.param(
            SourceRecoverySnapshot(unsafe_reason="native_content"),
            False,
            id="unsafe_before_release",
        ),
        pytest.param(
            SourceRecoverySnapshot(structured_output=True), True, id="structured"
        ),
    ],
)
async def test_unsafe_transitions_raise_without_falling_back(source, release):
    outcome = await _run(
        fails_after("a", failure=_failure(source), release=release), ok("b")
    )

    assert outcome.opened == [(0, None)]
    assert outcome.raised == 502
    assert outcome.fallbacks == []


@pytest.mark.asyncio
async def test_failure_without_context_after_own_delivery_raises():
    outcome = await _run(fails_after("a", failure=_failure(NO_CONTEXT)), ok("b"))

    assert outcome == Outcome(opened=[(0, None)], frames=["a"], raised=502)


@pytest.mark.asyncio
async def test_last_candidate_failure_raises():
    outcome = await _run(
        fails_after("a", failure=_failure(CLEAN)),
        open_fails(_failure(NO_CONTEXT, status=503)),
    )

    assert outcome.opened == [(0, None), (1, "a")]
    assert outcome.raised == 503
    assert outcome.fallbacks == [("continue", "portable_prefix")]


@pytest.mark.asyncio
async def test_silent_continuation_failure_without_context_keeps_the_seed():
    # Candidate 1 continues from "a", then fails before producing anything and
    # without stream context. The "a" seed is still valid for candidate 2.
    outcome = await _run(
        fails_after("a", failure=_failure(CLEAN)),
        open_fails(_failure(NO_CONTEXT, status=429)),
        ok("c"),
    )

    assert outcome == Outcome(
        opened=[(0, None), (1, "a"), (2, "a")],
        frames=["a", "c"],
        transition="continue",
        fallbacks=[
            ("continue", "portable_prefix"),
            ("continue", "no_candidate_output"),
        ],
        selected=[3],
    )


@pytest.mark.asyncio
async def test_continuation_failure_without_context_after_own_output_raises():
    outcome = await _run(
        fails_after("a", failure=_failure(CLEAN)),
        fails_after("b", failure=_failure(NO_CONTEXT, status=429)),
        ok("c"),
    )

    assert outcome.opened == [(0, None), (1, "a")]
    assert outcome.frames == ["a", "b"]
    assert outcome.raised == 429


@pytest.mark.asyncio
async def test_lmstudio_budget_rejection_of_a_continuation_keeps_the_seed():
    # LM Studio checks the prepared body against its loaded context before
    # sending. A continuation body carries the delivered prefix, so it can fail
    # that check locally, without stream context, before producing anything.
    def handler(request: httpx2.Request) -> httpx2.Response:
        if request.method == "GET":
            return metadata_response(context=1000)
        raise AssertionError("LM Studio must not send an over-budget body")

    delivered = "word " * 1000
    state = StreamDeliveryState()
    state.bind_prefix(
        lambda: DeliveredPrefix(
            text=delivered,
            thinking="",
            has_calls=False,
            eligible=True,
            can_handoff=True,
            unsafe_reason=None,
            continuation=ContinuationSeed(
                "messages", ({"type": "text", "text": delivered},)
            ),
        )
    )

    async def first() -> AsyncIterator[StreamOutput]:
        yield StreamOutput(("first",))
        state.release_content()
        raise _failure(CLEAN)

    async def last() -> AsyncIterator[StreamOutput]:
        yield StreamOutput(("last",))

    seeds: list[str | None] = []
    async with provider_with_http(handler) as lmstudio:

        async def open_candidate(index, _candidate, continuation):
            seeds.append(continuation.readable_text("text") if continuation else None)
            if index == 1:
                return lmstudio.stream_messages(
                    make_request(), continuation=continuation
                )
            return first() if index == 0 else last()

        candidates = tuple(
            ProviderModelCandidate(ProviderModelTarget("p", f"m{i}", f"p/m{i}"))
            for i in range(3)
        )
        with bind_stream_delivery(state):
            frames = [
                frame
                async for chunk in stream_model_candidates(
                    candidates,
                    open_candidate,
                    get_delivery=lambda: state,
                    request_id="lmstudio-budget",
                    wire_api="messages",
                )
                for frame in chunk.frames
            ]

    assert seeds == [None, delivered, delivered]
    assert frames == ["first", "last"]


@pytest.mark.asyncio
async def test_prefix_is_read_only_for_failures_with_stream_evidence():
    reads: list[str] = []
    outcome = await _run(
        fails_after("a", failure=_failure(CLEAN)),
        open_fails(_failure(NO_CONTEXT, status=429)),
        ok("c"),
        reads=reads,
    )

    assert outcome.frames == ["a", "c"]
    # Read once, for the first failure; the second carries no stream evidence.
    assert reads == ["a"]