Spaces:
Running
Running
File size: 10,890 Bytes
07f3ede 334ff81 af66f2f | 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 | """How a fal failure is classified.
Inherited from the Replicate version of this file, because the bug it was written
for is provider-independent: a real render died on a 500 from the API, the retry
decorators key on RuntimeError, the SDK's own exception is not one — so it was
retried ZERO times, and because callers only handle
ContentFlaggedError/ProviderError it surfaced as a raw traceback rather than as
"segment 3 failed: ...".
These pin both halves: transient means retried, permanent means surfaced, and
nothing escapes as a third exception type. Plus the one that matters most for
cost: a moderation refusal must never be retried, because it can never succeed
and the recovery ladder in prompt_safety is waiting for it.
"""
import httpx
import pytest
from fal_client import FalClientHTTPError, FalClientTimeoutError
from app.services import fal
from app.services.clip_edit import ClipEditError
from app.services.fal import ContentFlaggedError, ProviderError
from app.services.omnihuman import OmniHumanClient
from app.services.render import RenderError
from app.services.seedance import SeedanceClient
def err(status: int, detail: str = "Internal server error") -> FalClientHTTPError:
return FalClientHTTPError(
detail, status_code=status, response_headers={}, response=httpx.Response(status)
)
def boom(exc: Exception):
def raise_it():
raise exc
return raise_it
# --- classification -------------------------------------------------------- #
def test_the_500_that_broke_the_render_is_transient():
with pytest.raises(RuntimeError) as caught:
fal.guard("clip request", boom(err(500)))
assert not isinstance(caught.value, (ProviderError, ContentFlaggedError))
assert "HTTP 500" in str(caught.value)
@pytest.mark.parametrize("status", [408, 409, 425, 429, 500, 502, 503, 504])
def test_provider_side_statuses_are_retryable(status):
with pytest.raises(RuntimeError):
fal.guard("x", boom(err(status)))
@pytest.mark.parametrize("status", [400, 401, 403, 404, 422])
def test_client_side_statuses_are_not_retried(status):
"""Retrying a malformed request just spends the backoff to fail identically."""
with pytest.raises(ProviderError):
fal.guard("x", boom(err(status, "bad request")))
def test_a_moderation_rejection_is_still_a_flag():
with pytest.raises(ContentFlaggedError):
fal.guard("x", boom(err(400, "flagged by content moderation")))
def test_a_500_whose_body_mentions_moderation_is_still_transient():
"""Status wins over wording: a 5xx is the provider's fault even if its error
text happens to mention the moderation subsystem."""
with pytest.raises(RuntimeError):
fal.guard("x", boom(err(500, "moderation service unavailable")))
def test_a_queue_timeout_is_transient():
"""The generation outlived our patience rather than failing — the identical
request is worth sending again."""
with pytest.raises(RuntimeError):
fal.guard("x", boom(FalClientTimeoutError("timed out waiting")))
def test_a_network_drop_is_transient():
with pytest.raises(RuntimeError):
fal.guard("x", boom(OSError("connection reset by peer")))
def test_success_passes_the_value_through():
assert fal.guard("x", lambda: "ok") == "ok"
# --- the retry actually engages --------------------------------------------- #
class Flaky:
"""Fails with a 500 `fail_times` times, then returns a finished result."""
def __init__(self, fail_times: int, key: str = "video"):
self.fail_times = fail_times
self.key = key
self.calls = 0
self.endpoints: list[str] = []
self.arguments: list[dict] = []
def __call__(self, endpoint, arguments, *, what):
self.calls += 1
self.endpoints.append(endpoint)
self.arguments.append(arguments)
if self.calls <= self.fail_times:
raise RuntimeError(f"{what} failed (HTTP 500)")
return {self.key: {"url": "https://example.invalid/out.mp4"}}
@pytest.fixture
def no_sleep(monkeypatch):
"""The decorators wait 2s then 4s; don't spend that in a test."""
monkeypatch.setattr("tenacity.nap.time.sleep", lambda _s: None)
@pytest.fixture
def stub_fal(monkeypatch):
"""Neutralise the two things that touch the network, and hand back the fake
`run` so a test can assert what was sent."""
monkeypatch.setattr(fal, "download", lambda url: b"mp4-bytes")
monkeypatch.setattr(
fal, "upload", lambda data, *, content_type, file_name: f"https://up/{file_name}"
)
def install(flaky):
monkeypatch.setattr(fal, "run", flaky)
return flaky
return install
def test_a_one_off_500_is_retried_and_the_clip_succeeds(stub_fal, no_sleep):
flaky = stub_fal(Flaky(fail_times=1))
assert SeedanceClient().generate_clip(prompt="a cat", duration_seconds=5.0) == b"mp4-bytes"
assert flaky.calls == 2, "the first 500 should have been retried, not raised"
def test_a_persistent_500_gives_up_as_a_runtime_error(stub_fal, no_sleep):
flaky = stub_fal(Flaky(fail_times=99))
with pytest.raises(RuntimeError):
SeedanceClient().generate_clip(prompt="a cat", duration_seconds=5.0)
assert flaky.calls == 3, "stop_after_attempt(3)"
def test_a_content_flag_is_never_retried(stub_fal, no_sleep, monkeypatch):
"""The expensive mistake: a refusal can't succeed on attempt two, and
prompt_safety's ladder is waiting to rewrite the prompt instead."""
calls = {"n": 0}
def refuse(endpoint, arguments, *, what):
calls["n"] += 1
raise ContentFlaggedError("flagged by content moderation")
monkeypatch.setattr(fal, "run", refuse)
with pytest.raises(ContentFlaggedError):
SeedanceClient().generate_clip(prompt="a news anchor", duration_seconds=5.0)
assert calls["n"] == 1, "a moderation refusal must cost exactly one call"
def test_omnihuman_classifies_the_same_way(stub_fal, no_sleep):
flaky = stub_fal(Flaky(fail_times=1))
assert OmniHumanClient().animate(image=b"jpg", audio=b"mp3") == b"mp4-bytes"
assert flaky.calls == 2
# --- endpoint routing (new in Seedance 2.5) --------------------------------- #
def test_a_plain_clip_uses_text_to_video(stub_fal, no_sleep):
flaky = stub_fal(Flaky(fail_times=0))
SeedanceClient().generate_clip(prompt="a kitchen", duration_seconds=6.0)
assert flaky.endpoints[0].endswith("/text-to-video")
@pytest.mark.parametrize(
"kwarg, expected_key",
[
("reference_video", "video_urls"),
("reference_image", "image_urls"),
("reference_audio", "audio_urls"),
],
)
def test_any_reference_switches_to_reference_to_video(stub_fal, no_sleep, kwarg, expected_key):
"""2.5's text-to-video endpoint accepts no reference input at all, so sending
one there would be silently dropped or rejected — the continuity feature would
just stop working."""
flaky = stub_fal(Flaky(fail_times=0))
SeedanceClient().generate_clip(
prompt="a kitchen", duration_seconds=6.0, **{kwarg: b"bytes"}
)
assert flaky.endpoints[0].endswith("/reference-to-video")
assert expected_key in flaky.arguments[0]
def test_the_resolution_default_comes_from_settings(stub_fal, no_sleep):
from app.core.config import settings
flaky = stub_fal(Flaky(fail_times=0))
SeedanceClient().generate_clip(prompt="a kitchen", duration_seconds=6.0)
assert flaky.arguments[0]["resolution"] == settings.seedance_resolution == "480p"
@pytest.mark.parametrize(
"asked, expected", [(1.0, "4"), (4.0, "4"), (7.4, "7"), (15.0, "15"), (40.0, "15")]
)
def test_duration_is_clamped_to_the_supported_range(stub_fal, no_sleep, asked, expected):
flaky = stub_fal(Flaky(fail_times=0))
SeedanceClient().generate_clip(prompt="x", duration_seconds=asked)
assert flaky.arguments[0]["duration"] == expected
# --- output shapes fal returns --------------------------------------------- #
@pytest.mark.parametrize(
"payload",
[
{"video": {"url": "https://x/o.mp4"}},
{"video": "https://x/o.mp4"},
{"video": [{"url": "https://x/o.mp4"}]},
{"video": ["https://x/o.mp4"]},
],
)
def test_every_output_shape_yields_a_url(payload):
"""The generation is already paid for by the time this runs, so a shape
difference must not be what throws it away."""
assert fal.file_url(payload, "video", what="x") == "https://x/o.mp4"
@pytest.mark.parametrize("payload", [{}, {"video": None}, {"video": []}, {"video": {}}])
def test_a_missing_url_is_a_provider_error(payload):
with pytest.raises(ProviderError):
fal.file_url(payload, "video", what="x")
# --- callers turn an exhausted retry into a readable message --------------- #
def test_render_and_clip_edit_handle_an_exhausted_retry():
"""`reraise=True` hands back the RuntimeError. Both callers must catch it, or
the user gets a traceback instead of which segment failed."""
for handler, wrapper in ((RenderError, "render"), (ClipEditError, "clip_edit")):
try:
try:
raise RuntimeError("Seedance clip request failed (HTTP 500)")
except (ProviderError, RuntimeError) as exc: # the clause both use
raise handler(f"failed: {exc}") from exc
except handler as exc:
assert "HTTP 500" in str(exc), wrapper
def test_a_network_error_from_httpx_is_transient_and_retried():
"""fal_client speaks httpx, whose timeouts and dropped connections are not
OSErrors. A TLS handshake timeout on the upload-token refresh escaped as a raw
traceback and killed a render at clip 9 of 11 — with retries that would have
covered a blip sitting one exception class away."""
for exc in (
httpx.ConnectTimeout("_ssl.c:1015: The handshake operation timed out"),
httpx.ReadTimeout("timed out"),
httpx.ConnectError("connection refused"),
httpx.RemoteProtocolError("server disconnected"),
):
with pytest.raises(RuntimeError, match="network"):
fal.guard("upload of reference1.jpg", boom(exc))
def test_a_refusal_that_echoes_a_transient_looking_prompt_is_still_a_content_flag():
"""fal echoes the request in the error. "internal buzz" in the spoken line
must not turn a moderation refusal into an "internal error" to retry."""
detail = ("[{'loc': ['body', 'video_urls'], 'msg': 'The images or videos provided may contain "
"likenesses of real people', 'type': 'content_policy_violation', 'input': {'prompt': "
"'she says: that high-pitched internal buzz in my ears'}}]")
with pytest.raises(fal.ContentFlaggedError):
fal.guard("clip", boom(err(422, detail)))
with pytest.raises(RuntimeError): # a real 503 is still retried, whatever it says
fal.guard("clip", boom(err(503, "likeness")))
|