From ada92933587c0f289ea3e8b1d89cad1c15e3acb9 Mon Sep 17 00:00:00 2001 From: CJstate <1507965754@qq.com> Date: Mon, 9 Nov 2026 11:32:05 +0800 Subject: [PATCH] fix(idempotency): compute the Redis orphan lock timeout from the configured expiry The lock timeout was cached in __init__ before configure() applied IdempotencyConfig, so min(10, 3600) always produced 10 seconds. Compute it in _acquire_lock from the configured expires_after_seconds instead. --- .../idempotency/persistence/redis.py | 8 +++- .../idempotency/_redis/test_redis_layer.py | 47 +++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/aws_lambda_powertools/utilities/idempotency/persistence/redis.py b/aws_lambda_powertools/utilities/idempotency/persistence/redis.py index bc3d626f3c6..b07004deb02 100644 --- a/aws_lambda_powertools/utilities/idempotency/persistence/redis.py +++ b/aws_lambda_powertools/utilities/idempotency/persistence/redis.py @@ -315,7 +315,6 @@ def lambda_handler(event: dict, context: LambdaContext): self._json_serializer = json.dumps self._json_deserializer = json.loads super().__init__() - self._orphan_lock_timeout = min(10, self.expires_after_seconds) def _get_expiry_second(self, expiry_timestamp: int | None = None) -> int: """ @@ -461,7 +460,12 @@ def _acquire_lock(self, name: str): the lock is only set if it does not already exist, thereby enforcing mutual exclusion. """ try: - acquired = self.client.set(name=f"{name}:lock", value="True", ex=self._orphan_lock_timeout, nx=True) + acquired = self.client.set( + name=f"{name}:lock", + value="True", + ex=min(10, self.expires_after_seconds), + nx=True, + ) logger.debug("acquiring lock to overwrite orphan record") if acquired: logger.debug("lock acquired") diff --git a/tests/functional/idempotency/_redis/test_redis_layer.py b/tests/functional/idempotency/_redis/test_redis_layer.py index 254ca94f580..baa5ec3e81c 100644 --- a/tests/functional/idempotency/_redis/test_redis_layer.py +++ b/tests/functional/idempotency/_redis/test_redis_layer.py @@ -873,3 +873,50 @@ def test_redis_client_protocol_still_emits_deprecation_warning_on_subclass(): with pytest.warns(DeprecationWarning, match="RedisClientProtocol will be removed in v4.0.0"): class MyClient(RedisClientProtocol): ... + + +@pytest.mark.parametrize("expires_after_seconds, want_lock_ex", [(2, 2), (30, 10)]) +def test_orphan_lock_ttl_follows_configured_expiry(expires_after_seconds, want_lock_ex, lambda_context): + """The orphan lock must live no longer than the record it protects.""" + + class RecordingRedis(MockRedis): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.set_calls = [] + + def set(self, name, value, ex: int = 0, nx: bool = False): + self.set_calls.append((name, ex)) + return super().set(name, value, ex=ex, nx=nx) + + redis_client = RecordingRedis(host="localhost", port="63005") + persistence_layer = CachePersistenceLayer(client=redis_client) + + # An INPROGRESS record from an invocation that timed out before finishing. + orphan = json.dumps( + { + "status": STATUS_CONSTANTS["INPROGRESS"], + "expiration": int(t.time()) + expires_after_seconds, + "in_progress_expiration": int(t.time() * 1000) - 1, + }, + ) + config = IdempotencyConfig(expires_after_seconds=expires_after_seconds) + mock_event = {"user_id": "orphan-lock-ttl"} + + @idempotent(persistence_store=persistence_layer, config=config) + def lambda_handler(event, context): + return {"message": "ok"} + + # The orphan record uses the hashed idempotency key, which the first call + # generates. Seed it by letting the decorator compute the key via a first + # call, then replace that record with the orphan and call again. + lambda_handler(mock_event, lambda_context) + record_key = next(name for name, _ in reversed(redis_client.set_calls) if not name.endswith(":lock")) + redis_client.cache[record_key] = orphan.encode() + redis_client.expire_dict[record_key] = t.time() + expires_after_seconds + + lock_before = len([c for c in redis_client.set_calls if c[0].endswith(":lock")]) + lambda_handler(mock_event, lambda_context) + + lock_calls = [c for c in redis_client.set_calls if c[0].endswith(":lock")] + assert len(lock_calls) > lock_before, "orphan record did not trigger a lock acquisition" + assert lock_calls[-1][1] == want_lock_ex, f"lock ex={lock_calls[-1][1]}, want {want_lock_ex}"