creative-brain-os / tests /test_fal_errors.py
kpranav022's picture
Claude Fable 5.1
Ask one question at a time, show the wait, let the brief lead, and keep refusals, faces and voices in hand
af66f2f
Raw History Blame Contribute Delete
10.9 kB
"""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")))