Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
fix: maintenance update (#43900)
-LAN-5671e03c8774
diff --git a/api/extensions/ext_redis.py b/api/extensions/ext_redis.pyindex 9b271178163..870d265da73 100644--- a/api/extensions/ext_redis.py+++ b/api/extensions/ext_redis.py@@ -210,6 +210,9 @@ class RedisClientWrapper:lt=lt,)+ def zrem(self, name: str | bytes, *values: str | bytes) -> Any:+ return self._require_client().zrem(_serialize_redis_name_arg(name, self._get_prefix()), *values)+def zremrangebyscore(self, name: str | bytes, min: float | str, max: float | str) -> Any:return self._require_client().zremrangebyscore(_serialize_redis_name_arg(name, self._get_prefix()), min, max)diff --git a/api/libs/helper.py b/api/libs/helper.pyindex 8734aba909f..858f78d0281 100644--- a/api/libs/helper.py+++ b/api/libs/helper.py@@ -8,6 +8,7 @@ import subprocessimport timeimport uuidfrom collections.abc import Callable, Generator, Iterable, Mapping+from contextlib import contextmanagerfrom datetime import datetimefrom hashlib import sha256from typing import TYPE_CHECKING, Annotated, Any, Protocol, cast, overload, override@@ -571,8 +572,12 @@ class TokenManager:class _RateLimiterRedisClient(Protocol):+ def register_script(self, script: str) -> Callable[..., Any]: ...+def zadd(self, name: str | bytes, mapping: dict[str | bytes | int | float, float | int | str | bytes]) -> int: ...+ def zrem(self, name: str | bytes, *values: str | bytes) -> int: ...+def zremrangebyscore(self, name: str | bytes, min: str | float, max: str | float) -> int: ...def zcard(self, name: str | bytes) -> int: ...@@ -603,6 +608,30 @@ class RateLimiter:def _get_key(self, email: str) -> str:return f"{self.prefix}:{email}"+ @contextmanager+ def reserve(self, email: str) -> Generator[bool]:+ """Reserve a slot atomically, releasing only this slot if the operation fails."""+ key = self._get_key(email)+ member = self._member_factory()+ script = self._redis_client.register_script("""+ redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1] - ARGV[2])+ if redis.call('ZSCORE', KEYS[1], ARGV[4]) then return 1 end+ if redis.call('ZCARD', KEYS[1]) >= tonumber(ARGV[3]) then return 0 end+ redis.call('ZADD', KEYS[1], ARGV[1], ARGV[4])+ redis.call('EXPIRE', KEYS[1], ARGV[2] * 2)+ return 1+ """)+ acquired = bool(script(keys=[key], args=[int(time.time()), self.time_window, self.max_attempts, member]))+ try:+ yield acquired+ except BaseException:+ if acquired:+ try:+ self._redis_client.zrem(key, member)+ except Exception:+ logger.exception("Failed to release rate limit reservation")+ raise+def is_rate_limited(self, email: str) -> bool:key = self._get_key(email)current_time = int(time.time())diff --git a/api/services/account/forgot_password_adapters.py b/api/services/account/forgot_password_adapters.pyindex 8882ffbd8ec..d72abfabb80 100644--- a/api/services/account/forgot_password_adapters.py+++ b/api/services/account/forgot_password_adapters.py@@ -2,6 +2,7 @@import secretsimport uuid+from contextlib import AbstractContextManagerfrom typing import overridefrom pydantic import TypeAdapter, ValidationError@@ -232,12 +233,8 @@ class RateLimiterForgotPasswordSendLimiter(ForgotPasswordSendLimiter):)@override- def is_limited(self, email: str) -> bool:- return self._rate_limiter.is_rate_limited(email)-- @override- def record(self, email: str) -> None:- self._rate_limiter.increment_rate_limit(email)+ def reserve(self, email: str) -> AbstractContextManager[bool]:+ return self._rate_limiter.reserve(email)@property@overridediff --git a/api/services/account/forgot_password_service.py b/api/services/account/forgot_password_service.pyindex c0a76c4bedc..2525ae31be9 100644--- a/api/services/account/forgot_password_service.py+++ b/api/services/account/forgot_password_service.py@@ -1,5 +1,6 @@"""Application service implementing the account forgot-password use case."""+from contextlib import AbstractContextManagerfrom typing import Protocolfrom services.account_errors import (@@ -54,9 +55,7 @@ class ForgotPasswordNotificationGateway(Protocol):class ForgotPasswordSendLimiter(Protocol):- def is_limited(self, email: str) -> bool: ...-- def record(self, email: str) -> None: ...+ def reserve(self, email: str) -> AbstractContextManager[bool]: ...@propertydef retry_after_minutes(self) -> int: ...@@ -115,25 +114,25 @@ class AccountForgotPasswordService:raise AccountNotFoundErrordestination = account.email if account is not None else normalized_emailregistration_allowed = self._registration.is_registration_allowed()- if self._send_limits.is_limited(destination):- raise ForgotPasswordSendRateLimitError(self._send_limits.retry_after_minutes)-- code = self._codes.generate()- token = self._tokens.issue(- ForgotPasswordVerificationToken(+ with self._send_limits.reserve(destination) as acquired:+ if not acquired:+ raise ForgotPasswordSendRateLimitError(self._send_limits.retry_after_minutes)++ code = self._codes.generate()+ token = self._tokens.issue(+ ForgotPasswordVerificationToken(+ email=destination,+ code=code,+ account_id=account.id if account is not None else None,+ )+ )+ self._notifications.send(email=destination,code=code,- account_id=account.id if account is not None else None,+ language=language,+ account_exists=account is not None,+ registration_allowed=registration_allowed,)- )- self._notifications.send(- email=destination,- code=code,- language=language,- account_exists=account is not None,- registration_allowed=registration_allowed,- )- self._send_limits.record(destination)return tokendef verify_code(diff --git a/api/services/account/login_adapters.py b/api/services/account/login_adapters.pyindex dc06e5bb4d9..1d443dfa12b 100644--- a/api/services/account/login_adapters.py+++ b/api/services/account/login_adapters.py@@ -317,25 +317,25 @@ class RedisResetPasswordEmailGateway(ResetPasswordEmailGateway):language: str,registration_allowed: bool,) -> str:- if self._rate_limiter.is_rate_limited(email):- raise account_errors.ResetPasswordEmailRateLimitError(int(self._rate_limiter.time_window / 60))-- code = "".join(str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6))- token = TokenManager.generate_token(- account_id=account_id,- email=email,- token_type="reset_password",- additional_data={"code": code},- )- if account_id is not None:- send_reset_password_mail_task.delay(language=language, to=email, code=code)- else:- send_reset_password_mail_task_when_account_not_exist.delay(- language=language,- to=email,- is_allow_register=registration_allowed,+ with self._rate_limiter.reserve(email) as acquired:+ if not acquired:+ raise account_errors.ResetPasswordEmailRateLimitError(int(self._rate_limiter.time_window / 60))++ code = "".join(str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6))+ token = TokenManager.generate_token(+ account_id=account_id,+ email=email,+ token_type="reset_password",+ additional_data={"code": code},)- self._rate_limiter.increment_rate_limit(email)+ if account_id is not None:+ send_reset_password_mail_task.delay(language=language, to=email, code=code)+ else:+ send_reset_password_mail_task_when_account_not_exist.delay(+ language=language,+ to=email,+ is_allow_register=registration_allowed,+ )return tokendiff --git a/api/services/web_authentication_adapters.py b/api/services/web_authentication_adapters.pyindex 5e9f1b6e464..f24dd5b6267 100644--- a/api/services/web_authentication_adapters.py+++ b/api/services/web_authentication_adapters.py@@ -86,20 +86,20 @@ class TokenManagerWebAuthenticationGateway(WebAuthenticationTokenGateway):@overridedef send_reset_password_code(self, *, account_id: str, email: str, language: str) -> str:limiter = self._reset_password_rate_limiter- if limiter.is_rate_limited(email):- raise WebEmailDeliveryRateLimitError(- flow="reset_password",- retry_after_minutes=int(limiter.time_window / 60),+ with limiter.reserve(email) as acquired:+ if not acquired:+ raise WebEmailDeliveryRateLimitError(+ flow="reset_password",+ retry_after_minutes=int(limiter.time_window / 60),+ )+ code = self._generate_code()+ token = TokenManager.generate_token(+ account_id=account_id,+ email=email,+ token_type="reset_password",+ additional_data={"code": code},)- code = self._generate_code()- token = TokenManager.generate_token(- account_id=account_id,- email=email,- token_type="reset_password",- additional_data={"code": code},- )- send_reset_password_mail_task.delay(language=language, to=email, code=code)- limiter.increment_rate_limit(email)+ send_reset_password_mail_task.delay(language=language, to=email, code=code)return token@overridediff --git a/api/tests/test_containers_integration_tests/libs/test_rate_limiter_integration.py b/api/tests/test_containers_integration_tests/libs/test_rate_limiter_integration.pyindex 390795486b9..9c1e9dc34b6 100644--- a/api/tests/test_containers_integration_tests/libs/test_rate_limiter_integration.py+++ b/api/tests/test_containers_integration_tests/libs/test_rate_limiter_integration.py@@ -3,6 +3,7 @@ Integration tests for RateLimiter using testcontainers Redis."""import uuid+from collections.abc import Callableimport pytest@@ -11,7 +12,7 @@ from libs import helper as helper_module@pytest.mark.usefixtures("flask_app_with_containers")-def test_rate_limiter_counts_multiple_attempts_in_same_second(monkeypatch: pytest.MonkeyPatch):+def test_rate_limiter_counts_multiple_attempts_in_same_second(monkeypatch: pytest.MonkeyPatch) -> None:prefix = f"test_rate_limit:{uuid.uuid4().hex}"limiter = helper_module.RateLimiter(prefix=prefix, max_attempts=2, time_window=60)key = limiter._get_key("203.0.113.10")@@ -23,3 +24,96 @@ def test_rate_limiter_counts_multiple_attempts_in_same_second(monkeypatch: pyteslimiter.increment_rate_limit("203.0.113.10")assert limiter.is_rate_limited("203.0.113.10") is True++[email protected]("flask_app_with_containers")+def test_reservation_admits_only_one_parallel_send() -> None:+ from concurrent.futures import ThreadPoolExecutor+ from threading import Barrier++ limiter = helper_module.RateLimiter(prefix=f"test_rate_limit:{uuid.uuid4().hex}", max_attempts=1, time_window=60)+ ready = Barrier(16)++ def reserve(_index: int) -> bool:+ ready.wait(timeout=10)+ with limiter.reserve("[email protected]") as acquired:+ return acquired++ with ThreadPoolExecutor(max_workers=16) as executor:+ admitted = list(executor.map(reserve, range(16)))++ assert sum(admitted) == 1+ assert redis_client.zcard(limiter._get_key("[email protected]")) == 1++[email protected]("flask_app_with_containers")+def test_reservation_preserves_window_expiry_and_failed_send_retry(monkeypatch: pytest.MonkeyPatch) -> None:+ limiter = helper_module.RateLimiter(prefix=f"test_rate_limit:{uuid.uuid4().hex}", max_attempts=1, time_window=60)+ email = "[email protected]"+ key = limiter._get_key(email)+ monkeypatch.setattr(helper_module.time, "time", lambda: 1000)++ def failed_send() -> None:+ with limiter.reserve(email) as acquired:+ assert acquired+ raise RuntimeError("queue unavailable")++ with pytest.raises(RuntimeError, match="queue unavailable"):+ failed_send()+ assert redis_client.zcard(key) == 0++ with limiter.reserve(email) as acquired:+ assert acquired+ with limiter.reserve(email) as acquired:+ assert not acquired+ assert 0 < redis_client.ttl(key) <= 120++ monkeypatch.setattr(helper_module.time, "time", lambda: 1059)+ with limiter.reserve(email) as acquired:+ assert not acquired+ monkeypatch.setattr(helper_module.time, "time", lambda: 1060)+ with limiter.reserve(email) as acquired:+ assert acquired+ assert redis_client.zcard(key) == 1++[email protected]("flask_app_with_containers")+def test_expired_reservation_failure_does_not_remove_later_send(monkeypatch: pytest.MonkeyPatch) -> None:+ limiter = helper_module.RateLimiter(prefix=f"test_rate_limit:{uuid.uuid4().hex}", max_attempts=1, time_window=60)+ email = "[email protected]"+ monkeypatch.setattr(helper_module.time, "time", lambda: 1000)++ def overlapping_sends() -> None:+ with limiter.reserve(email) as acquired:+ assert acquired+ monkeypatch.setattr(helper_module.time, "time", lambda: 1060)+ with limiter.reserve(email) as new_acquired:+ assert new_acquired+ raise RuntimeError("original send failed")++ with pytest.raises(RuntimeError, match="original send failed"):+ overlapping_sends()++ with limiter.reserve(email) as acquired:+ assert not acquired+ assert redis_client.zcard(limiter._get_key(email)) == 1++[email protected]("flask_app_with_containers")+def test_reservation_command_retry_is_idempotent(monkeypatch: pytest.MonkeyPatch) -> None:+ limiter = helper_module.RateLimiter(prefix=f"test_rate_limit:{uuid.uuid4().hex}", max_attempts=1, time_window=60)+ register_script = redis_client.register_script++ def replay_registration(script: str) -> Callable[..., object]:+ execute = register_script(script)++ def execute_twice(*, keys: list[str], args: list[object]) -> object:+ execute(keys=keys, args=args)+ return execute(keys=keys, args=args)++ return execute_twice++ monkeypatch.setattr(redis_client, "register_script", replay_registration)+ with limiter.reserve("[email protected]") as acquired:+ assert acquired+ assert redis_client.zcard(limiter._get_key("[email protected]")) == 1diff --git a/api/tests/unit_tests/extensions/test_redis.py b/api/tests/unit_tests/extensions/test_redis.pyindex 8f5f03924cc..3ea0de346d9 100644--- a/api/tests/unit_tests/extensions/test_redis.py+++ b/api/tests/unit_tests/extensions/test_redis.py@@ -59,6 +59,9 @@ class _RecordingRedisClient:def zadd(self, name: str | bytes, mapping: Mapping[object, object], **kwargs: object) -> None:self._record("zadd", name, mapping, **kwargs)+ def zrem(self, name: str | bytes, *values: str | bytes) -> None:+ self._record("zrem", name, *values)+@pytest.fixture(autouse=True)def _redis_config(config_overrides: Callable[..., None]) -> None:@@ -192,6 +195,16 @@ class TestRedisKeyPrefixHelpers:class TestRedisClientWrapperKeyPrefix:+ def test_wrapper_zrem_prefixes_key_but_not_members(self, config_overrides: Callable[..., None]) -> None:+ client = _RecordingRedisClient()+ wrapper = RedisClientWrapper()+ wrapper.initialize(client) # type: ignore[arg-type]+ config_overrides(REDIS_KEY_PREFIX="enterprise-a")++ wrapper.zrem("reset:[email protected]", "reservation")++ assert client.calls == [("zrem", ("enterprise-a:reset:[email protected]", "reservation"), {})]+def test_wrapper_registered_script_prefixes_key_arguments(self, config_overrides: Callable[..., None]) -> None:raw_client = _RecordingRedisClient()wrapper = RedisClientWrapper()diff --git a/api/tests/unit_tests/libs/test_rate_limiter.py b/api/tests/unit_tests/libs/test_rate_limiter.pyindex 5052033db87..378cf88b1d4 100644--- a/api/tests/unit_tests/libs/test_rate_limiter.py+++ b/api/tests/unit_tests/libs/test_rate_limiter.py@@ -1,7 +1,9 @@+from typing import castfrom unittest.mock import MagicMockimport pytest+from extensions.ext_redis import RedisClientWrapperfrom libs import helper as helper_module@@ -13,7 +15,7 @@ class _FakeRedis:def zadd(self, key: str, mapping: dict[str, float]) -> int:zset = self._zsets.setdefault(key, {})for member, score in mapping.items():- zset[str(member)] = float(score)+ zset[member] = float(score)return len(mapping)def zremrangebyscore(self, key: str, min_score: str | float, max_score: str | float) -> int:@@ -33,7 +35,7 @@ class _FakeRedis:return True-def test_rate_limiter_counts_attempts_within_same_second(monkeypatch: pytest.MonkeyPatch):+def test_rate_limiter_counts_attempts_within_same_second(monkeypatch: pytest.MonkeyPatch) -> None:fake_redis = _FakeRedis()monkeypatch.setattr(helper_module.time, "time", lambda: 1000)@@ -41,7 +43,7 @@ def test_rate_limiter_counts_attempts_within_same_second(monkeypatch: pytest.Monprefix="test_rate_limit",max_attempts=2,time_window=60,- redis_client=fake_redis,+ redis_client=cast(helper_module._RateLimiterRedisClient, fake_redis),)limiter.increment_rate_limit("203.0.113.10")@@ -50,7 +52,7 @@ def test_rate_limiter_counts_attempts_within_same_second(monkeypatch: pytest.Monassert limiter.is_rate_limited("203.0.113.10") is True-def test_rate_limiter_uses_injected_redis(monkeypatch: pytest.MonkeyPatch):+def test_rate_limiter_uses_injected_redis(monkeypatch: pytest.MonkeyPatch) -> None:redis_client = MagicMock()redis_client.zcard.return_value = 1monkeypatch.setattr(helper_module.time, "time", lambda: 1000)@@ -68,3 +70,60 @@ def test_rate_limiter_uses_injected_redis(monkeypatch: pytest.MonkeyPatch):assert redis_client.zadd.called is Trueassert redis_client.zremrangebyscore.called is Trueassert redis_client.zcard.called is True++[email protected]("acquired", [True, False])+def test_reservation_uses_one_atomic_command_and_keeps_successful_slots(+ redis_transport: tuple[RedisClientWrapper, MagicMock], monkeypatch: pytest.MonkeyPatch, acquired: bool+) -> None:+ redis, commands = redis_transport+ commands.return_value = int(acquired)+ monkeypatch.setattr(helper_module.time, "time", lambda: 1000)+ limiter = helper_module.RateLimiter(+ prefix="reset", max_attempts=1, time_window=60, member_factory=lambda: "reservation", redis_client=redis+ )++ with limiter.reserve("[email protected]") as allowed:+ assert allowed is acquired++ assert commands.call_count == 1+ assert commands.call_args.args[0] == "EVALSHA"+ assert commands.call_args.args[2:] == (1, "reset:[email protected]", 1000, 60, 1, "reservation")++[email protected]("acquired", [True, False])+def test_failed_reservation_releases_only_its_own_slot(+ redis_transport: tuple[RedisClientWrapper, MagicMock], acquired: bool+) -> None:+ redis, commands = redis_transport+ commands.return_value = int(acquired)+ limiter = helper_module.RateLimiter(+ prefix="reset", max_attempts=1, time_window=60, member_factory=lambda: "reservation", redis_client=redis+ )++ with pytest.raises(RuntimeError, match="delivery failed"), limiter.reserve("[email protected]"):+ raise RuntimeError("delivery failed")++ assert commands.call_count == (2 if acquired else 1)+ if acquired:+ assert commands.call_args.args == ("ZREM", "reset:[email protected]", "reservation")+++def test_reservation_cleanup_does_not_hide_delivery_error(+ redis_transport: tuple[RedisClientWrapper, MagicMock],+) -> None:+ redis, commands = redis_transport+ commands.side_effect = [1, ConnectionError("redis unavailable")]+ limiter = helper_module.RateLimiter(prefix="reset", max_attempts=1, time_window=60, redis_client=redis)++ with pytest.raises(RuntimeError, match="delivery failed"), limiter.reserve("[email protected]"):+ raise RuntimeError("delivery failed")+++def test_reservation_redis_failure_stops_the_operation(redis_transport: tuple[RedisClientWrapper, MagicMock]) -> None:+ redis, commands = redis_transport+ commands.side_effect = ConnectionError("redis unavailable")+ limiter = helper_module.RateLimiter(prefix="reset", max_attempts=1, time_window=60, redis_client=redis)++ with pytest.raises(ConnectionError, match="redis unavailable"), limiter.reserve("[email protected]"):+ pytest.fail("Operation must not run without acquiring a slot")diff --git a/api/tests/unit_tests/services/account/test_forgot_password_service.py b/api/tests/unit_tests/services/account/test_forgot_password_service.pyindex e5d54b7517e..6e728989bb0 100644--- a/api/tests/unit_tests/services/account/test_forgot_password_service.py+++ b/api/tests/unit_tests/services/account/test_forgot_password_service.py@@ -2,6 +2,8 @@from __future__ import annotations+from collections.abc import Generator+from contextlib import contextmanagerfrom datetime import datetimefrom typing import cast@@ -147,12 +149,12 @@ class FakeSendLimiter:self.checked: list[str] = []self.recorded: list[str] = []- def is_limited(self, email: str) -> bool:+ @contextmanager+ def reserve(self, email: str) -> Generator[bool]:self.checked.append(email)- return self.limited-- def record(self, email: str) -> None:- self.recorded.append(email)+ yield not self.limited+ if not self.limited:+ self.recorded.append(email)class FakeSecurity:@@ -521,3 +523,27 @@ def test_reset_rejects_account_when_email_changed_after_token_issue() -> None:)assert dependencies.accounts.updated is None++[email protected]("failure_stage", ["token", "notification"])+def test_send_code_propagates_failures_and_releases_reservation(+ monkeypatch: pytest.MonkeyPatch, failure_stage: str+) -> None:+ dependencies = Dependencies(_account())++ def fail(*_args: object, **_kwargs: object) -> None:+ raise RuntimeError("temporary failure")++ target, method = (+ (dependencies.tokens, "issue") if failure_stage == "token" else (dependencies.notifications, "send")+ )+ with monkeypatch.context() as patcher:+ patcher.setattr(target, method, fail)+ with pytest.raises(RuntimeError, match="temporary failure"):+ dependencies.service.send_code(email="[email protected]", language="en-US", ip_address="127.0.0.1")++ assert dependencies.send_limits.checked == ["[email protected]"]+ assert dependencies.send_limits.recorded == []+ dependencies.service.send_code(email="[email protected]", language="en-US", ip_address="127.0.0.1")+ assert dependencies.send_limits.recorded == ["[email protected]"]+ assert len(dependencies.notifications.sent) == 1diff --git a/api/tests/unit_tests/services/account/test_login_adapters.py b/api/tests/unit_tests/services/account/test_login_adapters.pyindex 95fd55570f3..170528ab5dd 100644--- a/api/tests/unit_tests/services/account/test_login_adapters.py+++ b/api/tests/unit_tests/services/account/test_login_adapters.py@@ -1,7 +1,8 @@from __future__ import annotationsimport logging-from collections.abc import Callable+from collections.abc import Callable, Generator+from contextlib import contextmanagerfrom dataclasses import dataclass, fieldfrom datetime import timedeltafrom typing import override@@ -42,6 +43,13 @@ class FakeRateLimiter(RateLimiter):def increment_rate_limit(self, email: str) -> None:self.recorded.append(email)+ @override+ @contextmanager+ def reserve(self, email: str) -> Generator[bool]:+ yield not self.limited+ if not self.limited:+ self.recorded.append(email)+@dataclassclass FakeTask:@@ -452,3 +460,35 @@ def test_email_gateways_raise_framework_neutral_rate_limit_errors() -> None:assert email_code_error.value.retry_after_minutes == 5assert reset_error.value.retry_after_minutes == 1++[email protected]("account_id", [None, "account-1"])[email protected]("failure_stage", ["token", "notification"])+def test_reset_password_gateway_releases_reservation_after_failure(+ redis_transport: tuple[RedisClientWrapper, MagicMock],+ monkeypatch: pytest.MonkeyPatch,+ account_id: str | None,+ failure_stage: str,+) -> None:+ redis, commands = redis_transport+ commands.return_value = 1+ limiter = RateLimiter(prefix="reset", max_attempts=1, time_window=60, redis_client=redis)+ gateway = adapters.RedisResetPasswordEmailGateway(rate_limiter=limiter)++ def generate_token(**_kwargs: object) -> str:+ if failure_stage == "token":+ raise RuntimeError("temporary failure")+ return "token"++ def queue_mail(**_kwargs: object) -> None:+ raise RuntimeError("temporary failure")++ monkeypatch.setattr(adapters.TokenManager, "generate_token", generate_token)+ monkeypatch.setattr(adapters.send_reset_password_mail_task, "delay", queue_mail)+ monkeypatch.setattr(adapters.send_reset_password_mail_task_when_account_not_exist, "delay", queue_mail)++ with pytest.raises(RuntimeError, match="temporary failure"):+ gateway.send(account_id=account_id, email="[email protected]", language="en-US", registration_allowed=True)++ assert commands.call_args_list[0].args[0] == "EVALSHA"+ assert commands.call_args_list[-1].args[:2] == ("ZREM", "reset:[email protected]")diff --git a/api/tests/unit_tests/services/test_web_authentication_adapters.py b/api/tests/unit_tests/services/test_web_authentication_adapters.pyindex cdb18e91824..7e8f2d41f27 100644--- a/api/tests/unit_tests/services/test_web_authentication_adapters.py+++ b/api/tests/unit_tests/services/test_web_authentication_adapters.py@@ -20,7 +20,7 @@ from services.web_authentication_service import WebEmailDeliveryRateLimitErrordef token_gateway(*, limited: bool = False) -> tuple[TokenManagerWebAuthenticationGateway, MagicMock]:limiter = MagicMock()- limiter.is_rate_limited.return_value = limited+ limiter.reserve.return_value.__enter__.return_value = not limitedlimiter.time_window = 600return (TokenManagerWebAuthenticationGateway(@@ -122,10 +122,10 @@ def test_send_reset_password_code_rejects_rate_limited_email() -> None:assert exc_info.value.retry_after_minutes == 10generate.assert_not_called()send_mail.assert_not_called()- limiter.increment_rate_limit.assert_not_called()+ limiter.reserve.assert_called_once_with("[email protected]")-def test_send_reset_password_code_persists_challenge_queues_mail_and_increments_limit() -> None:+def test_send_reset_password_code_persists_challenge_and_queues_mail_within_reservation() -> None:gateway, limiter = token_gateway()with (@@ -147,7 +147,8 @@ def test_send_reset_password_code_persists_challenge_queues_mail_and_increments_additional_data={"code": "654321"},)send_mail.assert_called_once_with(language="zh-Hans", to="[email protected]", code="654321")- limiter.increment_rate_limit.assert_called_once_with("[email protected]")+ limiter.reserve.assert_called_once_with("[email protected]")+ limiter.reserve.return_value.__exit__.assert_called_once_with(None, None, None)def test_token_lookup_returns_none_when_token_manager_has_no_data() -> None:@@ -541,3 +542,20 @@ def test_login_failure_audit_writes_structured_warning() -> None:LoginFailureReason.INVALID_CREDENTIALS,"203.0.113.1",)++[email protected]("failure_stage", ["token", "notification"])+def test_reset_password_failure_exits_the_reservation_with_the_original_error(failure_stage: str) -> None:+ gateway, limiter = token_gateway()+ error = RuntimeError("temporary failure")+ with (+ patch("services.web_authentication_adapters.TokenManager.generate_token", return_value="token") as generate,+ patch("services.web_authentication_adapters.send_reset_password_mail_task.delay") as send_mail,+ ):+ (generate if failure_stage == "token" else send_mail).side_effect = error+ with pytest.raises(RuntimeError, match="temporary failure"):+ gateway.send_reset_password_code(account_id="account-1", email="[email protected]", language="en-US")++ exit_args = limiter.reserve.return_value.__exit__.call_args.args+ assert exit_args[0] is RuntimeError+ assert exit_args[1] is error