mirror of
https://github.com/langgenius/dify.git
synced 2026-12-01 17:24:08 +08:00
fix(plugin): compact completed auto-upgrade reservations (#47377)
This commit is contained in:
2 files changed
+113
-25
No files matched your search
@@ -22,9 +22,11 @@ from pydantic import BaseModel, ConfigDict, Field
|
||||
MAX_CONCURRENT_CHECK_TASKS = 20
|
||||
CHECK_TASK_TIME_LIMIT = 30 * 60
|
||||
CHECK_SLOT_LEASE_SECONDS = CHECK_TASK_TIME_LIMIT + 60
|
||||
CHECK_QUEUE_DEADLINE_SECONDS = 24 * 60 * 60
|
||||
CHECK_QUEUE_DEADLINE_SECONDS = 3 * 60 * 60
|
||||
CHECK_INTERVAL_SECONDS = 15 * 60
|
||||
SCHEDULE_WINDOW_LEAD_SECONDS = 30
|
||||
_SECONDS_PER_DAY = 24 * 60 * 60
|
||||
_SCHEDULE_ANCHOR_TTL_SECONDS = 24 * 60 * 60
|
||||
|
||||
# All script keys share a Redis Cluster hash slot, even when a deployment adds
|
||||
# its own Redis namespace prefix. register_script applies that prefix for us.
|
||||
@@ -65,20 +67,23 @@ _RESERVE_SCRIPT = """
|
||||
local clock = redis.call('TIME')
|
||||
local now = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
|
||||
local deadline = tonumber(ARGV[2])
|
||||
if now >= deadline then
|
||||
return 0
|
||||
end
|
||||
if redis.call('EXISTS', KEYS[1]) == 1 then
|
||||
if redis.call('HGET', KEYS[1], 'token') == ARGV[1]
|
||||
and redis.call('HGET', KEYS[1], 'deadline') == ARGV[2]
|
||||
and redis.call('HGET', KEYS[1], 'state') == 'pending' then
|
||||
return 1
|
||||
-- A producer retry must recover the deadline written before a rollout.
|
||||
local existing_deadline = tonumber(redis.call('HGET', KEYS[1], 'deadline'))
|
||||
if existing_deadline and now < existing_deadline then
|
||||
return existing_deadline
|
||||
end
|
||||
end
|
||||
return 0
|
||||
end
|
||||
if now >= deadline then
|
||||
return 0
|
||||
end
|
||||
redis.call('HSET', KEYS[1], 'token', ARGV[1], 'deadline', ARGV[2], 'state', 'pending')
|
||||
redis.call('PEXPIREAT', KEYS[1], deadline)
|
||||
return 1
|
||||
return deadline
|
||||
"""
|
||||
|
||||
_SCHEDULE_ANCHOR_SCRIPT = """
|
||||
@@ -144,8 +149,9 @@ redis.call('ZREM', KEYS[2], KEYS[1])
|
||||
if redis.call('GET', KEYS[3]) == ARGV[1] .. ':' .. ARGV[2] then
|
||||
redis.call('DEL', KEYS[3])
|
||||
end
|
||||
-- Keep the hash type so workers using the original reservation scripts can read it.
|
||||
redis.call('HSET', KEYS[1], 'state', 'done')
|
||||
redis.call('HDEL', KEYS[1], 'execution_token')
|
||||
redis.call('HDEL', KEYS[1], 'token', 'deadline', 'execution_token')
|
||||
redis.call('PEXPIREAT', KEYS[1], tonumber(ARGV[3]))
|
||||
return 1
|
||||
"""
|
||||
@@ -173,7 +179,7 @@ def _execution_key(reservation: CheckReservation) -> str:
|
||||
|
||||
def _logical_day(upgrade_time_of_day: int, scheduled_at: float) -> str:
|
||||
"""Map a valid strategy in the producer's window to its UTC occurrence day."""
|
||||
if not 0 <= upgrade_time_of_day < CHECK_QUEUE_DEADLINE_SECONDS:
|
||||
if not 0 <= upgrade_time_of_day < _SECONDS_PER_DAY:
|
||||
raise ValueError("upgrade_time_of_day must be within one UTC day")
|
||||
if not math.isfinite(scheduled_at) or scheduled_at <= 0:
|
||||
raise ValueError("scheduled_at must be a positive finite Unix timestamp")
|
||||
@@ -205,7 +211,7 @@ class RedisPluginAutoUpgradeCoordinator:
|
||||
if not math.isfinite(scheduled_at) or scheduled_at <= 0:
|
||||
raise ValueError("scheduled_at must be a positive finite Unix timestamp")
|
||||
producer_key = f"{_KEY_PREFIX}:producer:{hashlib.sha256(producer_id.encode()).hexdigest()}"
|
||||
anchor = self._schedule_anchor(keys=[producer_key], args=[repr(scheduled_at), CHECK_QUEUE_DEADLINE_SECONDS])
|
||||
anchor = self._schedule_anchor(keys=[producer_key], args=[repr(scheduled_at), _SCHEDULE_ANCHOR_TTL_SECONDS])
|
||||
return float(anchor)
|
||||
|
||||
def reserve(
|
||||
@@ -218,11 +224,12 @@ class RedisPluginAutoUpgradeCoordinator:
|
||||
) -> CheckReservation | None:
|
||||
"""Reserve a scheduled check until its deadline, or return None if already reserved.
|
||||
|
||||
A reservation covers queued, running, and completed deliveries. With a
|
||||
stable producer_id, the same producer can recover a pending reservation
|
||||
after losing Redis's reply or crashing before publication. The caller
|
||||
must retain scheduled_at on retry and mark successful publication queued.
|
||||
Redis errors propagate instead of permitting uncoordinated work.
|
||||
A new check can start within three hours of scheduling and deduplicates
|
||||
until that deadline. With a stable producer_id, the same producer can
|
||||
recover a pending reservation and its original deadline after losing
|
||||
Redis's reply or crashing before publication. The caller must retain
|
||||
scheduled_at on retry and mark successful publication queued. Redis errors
|
||||
propagate instead of permitting uncoordinated work.
|
||||
"""
|
||||
if producer_id == "":
|
||||
raise ValueError("producer_id must not be empty when provided")
|
||||
@@ -238,10 +245,19 @@ class RedisPluginAutoUpgradeCoordinator:
|
||||
token=token,
|
||||
deadline=scheduled_at + CHECK_QUEUE_DEADLINE_SECONDS,
|
||||
)
|
||||
reserved = self._reserve(
|
||||
keys=[_reservation_key(reservation)], args=[reservation.token, int(reservation.deadline * 1000)]
|
||||
deadline_ms = int(reservation.deadline * 1000)
|
||||
reserved_deadline_ms = int(
|
||||
self._reserve(keys=[_reservation_key(reservation)], args=[reservation.token, deadline_ms])
|
||||
)
|
||||
return reservation if int(reserved) == 1 else None
|
||||
if not reserved_deadline_ms:
|
||||
return None
|
||||
if reserved_deadline_ms != deadline_ms:
|
||||
recovered_deadline = reserved_deadline_ms / 1000
|
||||
# Acquire compares integer milliseconds, including on older workers.
|
||||
if int(recovered_deadline * 1000) < reserved_deadline_ms:
|
||||
recovered_deadline = math.nextafter(recovered_deadline, math.inf)
|
||||
return reservation.model_copy(update={"deadline": recovered_deadline})
|
||||
return reservation
|
||||
|
||||
def mark_queued(self, reservation: CheckReservation) -> None:
|
||||
"""Mark only this producer's pending reservation published, preserving running or completed work."""
|
||||
@@ -261,7 +277,7 @@ class RedisPluginAutoUpgradeCoordinator:
|
||||
up to one check interval before their configured time or delayed after
|
||||
it; select that occurrence instead of incorrectly reserving tomorrow.
|
||||
"""
|
||||
if not 0 <= upgrade_time_of_day < CHECK_QUEUE_DEADLINE_SECONDS:
|
||||
if not 0 <= upgrade_time_of_day < _SECONDS_PER_DAY:
|
||||
raise ValueError("upgrade_time_of_day must be within one UTC day")
|
||||
if not math.isfinite(now) or now <= 0:
|
||||
raise ValueError("now must be a positive finite Unix timestamp")
|
||||
@@ -300,7 +316,7 @@ class RedisPluginAutoUpgradeCoordinator:
|
||||
}[int(result)]
|
||||
|
||||
def finish(self, reservation: CheckReservation, execution_token: str) -> None:
|
||||
"""Release only this execution and retain its completed deduplication marker until the deadline."""
|
||||
"""Release the matching execution and keep only its done state until the original deadline."""
|
||||
self._finish(
|
||||
keys=[_reservation_key(reservation), _SLOTS_KEY, _execution_key(reservation)],
|
||||
args=[reservation.token, execution_token, int(reservation.deadline * 1000)],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Exercise the distributed admission protocol against actual Redis Lua scripts."""
|
||||
|
||||
import math
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import UTC, datetime, timedelta
|
||||
@@ -8,8 +9,10 @@ import pytest
|
||||
from redis.exceptions import ConnectionError
|
||||
|
||||
from extensions.ext_redis import RedisClientWrapper
|
||||
from tasks import plugin_autoupgrade_coordination
|
||||
from tasks.plugin_autoupgrade_coordination import (
|
||||
_SLOTS_KEY,
|
||||
CHECK_QUEUE_DEADLINE_SECONDS,
|
||||
CHECK_SLOT_LEASE_SECONDS,
|
||||
CHECK_TASK_TIME_LIMIT,
|
||||
MAX_CONCURRENT_CHECK_TASKS,
|
||||
@@ -91,6 +94,48 @@ def test_producer_redelivery_keeps_the_original_window_anchor(application_redis:
|
||||
assert coordinator.schedule_anchor("other-parent-task", seconds + 16 * 60) == seconds + 16 * 60
|
||||
|
||||
|
||||
def test_producer_redelivery_cannot_create_a_reservation_after_three_hours(
|
||||
application_redis: RedisClientWrapper,
|
||||
) -> None:
|
||||
"""A replay after its queue deadline uses the old window and cannot publish a new check."""
|
||||
coordinator = RedisPluginAutoUpgradeCoordinator(application_redis)
|
||||
seconds, _ = application_redis.time()
|
||||
scheduled_at = seconds - 3 * 3600
|
||||
time_of_day = scheduled_at % (24 * 3600)
|
||||
coordinator.schedule_anchor("parent-task", scheduled_at)
|
||||
anchor = coordinator.schedule_anchor("parent-task", seconds)
|
||||
|
||||
assert anchor == scheduled_at
|
||||
assert coordinator.reserve("tenant", "tool", time_of_day, anchor, producer_id="parent-task") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fixed_scheduled_at",
|
||||
[None, math.nextafter(2_147_483_648.002, math.inf) - 24 * 3600],
|
||||
ids=["late-retry", "millisecond-round-trip"],
|
||||
)
|
||||
def test_producer_retry_recovers_a_pending_reservation_with_its_old_deadline(
|
||||
application_redis: RedisClientWrapper, monkeypatch: pytest.MonkeyPatch, fixed_scheduled_at: float | None
|
||||
) -> None:
|
||||
"""A retry after rollout can publish a pending 24-hour reservation under its original deadline."""
|
||||
coordinator = RedisPluginAutoUpgradeCoordinator(application_redis)
|
||||
seconds, _ = application_redis.time()
|
||||
scheduled_at = seconds - 4 * 3600 if fixed_scheduled_at is None else fixed_scheduled_at
|
||||
time_of_day = int(scheduled_at % (24 * 3600))
|
||||
with monkeypatch.context() as overrides:
|
||||
overrides.setattr(plugin_autoupgrade_coordination, "CHECK_QUEUE_DEADLINE_SECONDS", 24 * 3600)
|
||||
original = coordinator.reserve("tenant", "tool", time_of_day, scheduled_at, producer_id="parent-task")
|
||||
|
||||
assert original is not None
|
||||
assert original.deadline == scheduled_at + 24 * 3600
|
||||
assert coordinator.reserve("tenant", "tool", time_of_day, scheduled_at, producer_id="other-parent") is None
|
||||
recovered = coordinator.reserve("tenant", "tool", time_of_day, scheduled_at, producer_id="parent-task")
|
||||
assert recovered is not None
|
||||
assert int(recovered.deadline * 1000) == int(original.deadline * 1000)
|
||||
coordinator.mark_queued(recovered)
|
||||
assert coordinator.acquire(recovered, "execution") == AcquireResult.ACQUIRED
|
||||
|
||||
|
||||
def test_legacy_reservation_recovers_a_lost_reply_with_its_task_identity(
|
||||
application_redis: RedisClientWrapper,
|
||||
) -> None:
|
||||
@@ -122,7 +167,7 @@ def test_successful_publication_is_not_repeated_after_queued_reply_is_lost(
|
||||
with pytest.raises(ConnectionError, match="reply was lost"):
|
||||
failed_marker.mark_queued(reservation)
|
||||
|
||||
scheduled_at = reservation.deadline - 24 * 3600
|
||||
scheduled_at = reservation.deadline - CHECK_QUEUE_DEADLINE_SECONDS
|
||||
timestamp = datetime.fromtimestamp(scheduled_at, UTC)
|
||||
time_of_day = timestamp.hour * 3600 + timestamp.minute * 60 + timestamp.second
|
||||
assert coordinator.reserve("tenant", "tool", time_of_day, scheduled_at, producer_id="parent-task") is None
|
||||
@@ -133,7 +178,7 @@ def test_same_producer_does_not_republish_running_or_completed_work(application_
|
||||
"""Pending recovery never permits an existing execution or completed check to be published again."""
|
||||
coordinator = RedisPluginAutoUpgradeCoordinator(application_redis)
|
||||
reservation = _reserve(coordinator, application_redis, "tenant", producer_id="parent-task")
|
||||
scheduled_at = reservation.deadline - 24 * 3600
|
||||
scheduled_at = reservation.deadline - CHECK_QUEUE_DEADLINE_SECONDS
|
||||
timestamp = datetime.fromtimestamp(scheduled_at, UTC)
|
||||
time_of_day = timestamp.hour * 3600 + timestamp.minute * 60 + timestamp.second
|
||||
|
||||
@@ -145,6 +190,33 @@ def test_same_producer_does_not_republish_running_or_completed_work(application_
|
||||
assert coordinator.acquire(reservation, "redelivery") == AcquireResult.DUPLICATE
|
||||
|
||||
|
||||
def test_completion_discards_ownership_fields_and_restores_the_queue_deadline(
|
||||
application_redis: RedisClientWrapper,
|
||||
) -> None:
|
||||
"""A check finishing near its deadline keeps only the state and drops the extended lease TTL."""
|
||||
coordinator = RedisPluginAutoUpgradeCoordinator(application_redis)
|
||||
seconds, _ = application_redis.time()
|
||||
deadline = seconds + 60
|
||||
reservation = coordinator.reserve("tenant", "tool", 0, deadline - 3 * 3600)
|
||||
assert reservation is not None
|
||||
assert reservation.deadline == deadline
|
||||
key = _reservation_key(reservation)
|
||||
assert coordinator.acquire(reservation, "execution") == AcquireResult.ACQUIRED
|
||||
assert application_redis.pttl(key) > 60_000
|
||||
|
||||
coordinator.finish(reservation, "execution")
|
||||
|
||||
assert application_redis.hgetall(key) == {b"state": b"done"}
|
||||
before_seconds, before_microseconds = application_redis.time()
|
||||
ttl_ms = application_redis.pttl(key)
|
||||
after_seconds, after_microseconds = application_redis.time()
|
||||
before_ms = before_seconds * 1000 + before_microseconds // 1000
|
||||
after_ms = after_seconds * 1000 + after_microseconds // 1000
|
||||
assert ttl_ms > 0
|
||||
assert before_ms + ttl_ms <= deadline * 1000 <= after_ms + ttl_ms
|
||||
assert coordinator.acquire(reservation, "redelivery") == AcquireResult.DUPLICATE
|
||||
|
||||
|
||||
def test_pending_running_and_completed_work_share_one_deduplication_marker(
|
||||
application_redis: RedisClientWrapper,
|
||||
) -> None:
|
||||
@@ -252,7 +324,7 @@ def test_same_strategy_cannot_run_on_two_scheduled_days_at_once(application_redi
|
||||
"""A previous day's still-running check blocks the next day's check until its owner finishes."""
|
||||
coordinator = RedisPluginAutoUpgradeCoordinator(application_redis)
|
||||
previous = _reserve(coordinator, application_redis, "tenant")
|
||||
scheduled_at = previous.deadline - 24 * 3600
|
||||
scheduled_at = previous.deadline - CHECK_QUEUE_DEADLINE_SECONDS
|
||||
timestamp = datetime.fromtimestamp(scheduled_at, UTC)
|
||||
time_of_day = timestamp.hour * 3600 + timestamp.minute * 60 + timestamp.second
|
||||
next_day = coordinator.reserve("tenant", "tool", time_of_day, scheduled_at + 24 * 3600)
|
||||
@@ -271,7 +343,7 @@ def test_expired_previous_day_owner_cannot_release_next_days_running_mutex(
|
||||
"""Stale cleanup from another daily marker does not release a newer cross-day execution."""
|
||||
coordinator = RedisPluginAutoUpgradeCoordinator(application_redis)
|
||||
previous = _reserve(coordinator, application_redis, "tenant")
|
||||
scheduled_at = previous.deadline - 24 * 3600
|
||||
scheduled_at = previous.deadline - CHECK_QUEUE_DEADLINE_SECONDS
|
||||
timestamp = datetime.fromtimestamp(scheduled_at, UTC)
|
||||
time_of_day = timestamp.hour * 3600 + timestamp.minute * 60 + timestamp.second
|
||||
next_day = coordinator.reserve("tenant", "tool", time_of_day, scheduled_at + 24 * 3600)
|
||||
@@ -301,7 +373,7 @@ def test_cancelled_producer_cannot_delete_a_replacement_reservation(application_
|
||||
|
||||
coordinator.cancel(previous)
|
||||
coordinator.mark_queued(previous)
|
||||
scheduled_at = current.deadline - 24 * 3600
|
||||
scheduled_at = current.deadline - CHECK_QUEUE_DEADLINE_SECONDS
|
||||
timestamp = datetime.fromtimestamp(scheduled_at, UTC)
|
||||
time_of_day = timestamp.hour * 3600 + timestamp.minute * 60 + timestamp.second
|
||||
assert coordinator.reserve("tenant", "tool", time_of_day, scheduled_at, producer_id="current-parent") == current
|
||||
|
||||
Reference in new issue
Block a user