diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4cf48f23..9eae80d5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,11 +22,14 @@ jobs: name: Tests (Python ${{ matrix.python-version }}) runs-on: ${{ matrix.os }} timeout-minutes: 20 + env: + REDBEAT_TEST_REDIS_SERVER: /usr/bin/redis-server strategy: fail-fast: false max-parallel: 4 matrix: - os: [ubuntu-latest] #, windows-latest] tests fail on windows + # Python 3.9 builds are available for Ubuntu 24.04, not 26.04. + os: [ubuntu-24.04] python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] steps: @@ -45,8 +48,15 @@ jobs: python -m pip install --upgrade pip pip install -r requirements-dev.txt - - name: Run unittests - run: make unittests + - name: Install Redis test binary + run: | + sudo apt-get update + sudo apt-get install --no-install-recommends --yes redis-server + + - name: Run unit and isolated Redis tests + run: | + test -x "$REDBEAT_TEST_REDIS_SERVER" + make test lint: name: Lint diff --git a/CHANGES.txt b/CHANGES.txt index 0e1b02da..c1ecba29 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,3 +1,56 @@ +Splunk-maintained changes +------------------------------------ + These additions are maintained in splunk/redbeat and are recorded separately + from the upstream RedBeat release history below. + + - Add RedBeatSchedulerEntry.save_with_first_due() to create an interval + entry with an application-selected timezone-aware first due time. + Normalize it to UTC while preserving fractional seconds in metadata. + Store its definition, run metadata, due score and policy fingerprint + together, without allowing immediate execution to bypass that time. + - Add update_definition() to change a managed entry's payload without + moving its saved due time or replacing accepted immediate-run state. + - Preserve an optional opaque jitter_fingerprint on reload and support + first_run_kwargs for the first outgoing managed invocation only. + Later reservations continue the ordinary interval schedule. + - Guard managed reservations and definition updates against conflicting + Redis writes, changed run state and deletion. Preserve newer payloads + and immediate requests. Retry WATCH conflicts up to three total attempts. + Ordinary managed reservations do not rewrite an unchanged definition. + - Add the optional redbeat_entry_policy callback to select the following + due time and applied policy during reservation. Keep the current stored + run unchanged. Allow applications to adopt, replace or remove a policy + without adding their timing rules to RedBeat. + - Add request_run() for an application-selected managed refresh deadline. + Keep the earliest pending deadline and latest payload. Reuse the existing + immediate flag and interval metadata rather than a separate request record. + Due or overdue requests prompt selection without bypassing the due check. + - Add save_guarded() for ordinary entries that may acquire a managed policy. + Assign an entry_id on guarded creation and reject stale writes after + deletion and recreation under the same key. Keep existing legacy entries + without an identity unchanged instead of assigning one during reload. + Assign the caller's creation identity only after the Redis write succeeds. + - Raise EntryAlreadyExists, a ValueError subtype, when either creation API + finds a winning entry. First-due creation uses the same three-attempt + WATCH handling so callers can distinguish this race from invalid input. + - Store policy fingerprints and creation identities as JSON values so both + text and byte Redis responses use the same decoding path. + - Keep from_key() on the existing HGET pipeline pattern, without duplicate + identity reads or load-time retries. Remove the associated selection-error + handler and obsolete tests. Guarded writes retain their identity checks. + Non-transactional reads can still mix records during same-key replacement. + - Add unit and isolated Redis, Beat and worker integration coverage. + Cover following-run policies, managed refreshes, same-key replacement, + concurrent writes, legacy entries and Redis Cluster managed operations. + Run tests with pytest and retain Python 3.9 CI support by using Ubuntu + 24.04 test runners with an explicitly installed Redis test binary. + + Applications remain responsible for offset calculation and timing policy. + RedBeat supplies persistence and the optional following-run policy hook, + not a jitter configuration flag or application-specific lifecycle rules. + Entries without managed state or a policy requesting adoption retain their + existing scheduling path. + 2.4.2 (2026-07-27) --------------------- - bugfix, restore the pre-2.4.0 handling of options inherited from diff --git a/docs/design.rst b/docs/design.rst index 97d63ac8..3bccab93 100644 --- a/docs/design.rst +++ b/docs/design.rst @@ -71,3 +71,32 @@ As a result most datetime objects need to be timezone aware. due_at, returns aware datetime to_timestamp(), accepts aware datetime, returns seconds since epoch (UTC) score(), returns seconds since epoch for due_at + +Explicit interval deadlines +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The opt-in ``save_with_first_due()`` and ``request_run()`` methods accept +timezone-aware deadlines. RedBeat converts them to UTC before calculating the +matching interval anchor. Fractional seconds in the deadline and interval are +preserved in JSON metadata. These methods require a positive, non-relative +interval schedule. Calendar schedules and relative rounding do not use this +anchor calculation. Other scheduling APIs keep their existing behavior. + +The optional ``redbeat_entry_policy`` callback can select a following deadline +under the same rules. It does not move the current saved invocation. Applications +own their policy, including any jitter window, identity hashing, whole-second +rounding or exceptions for urgent work. RedBeat stores the supplied timing and +protects managed writes against concurrent updates and schedule replacement. + +Redis lookup scores retain their existing whole-second precision. A candidate +can therefore be selected before a fractional deadline. The full-precision due +check still prevents early publication. Beat wake-up frequency, broker latency +and worker capacity can delay dispatch or execution. Subsecond timing is not a +real-time execution guarantee. + +Entry loading follows the existing pipeline read pattern. Standalone Redis and +Sentinel use the client's default transactional pipeline. A non-transactional +read, including a default Cluster pipeline, does not guarantee a consistent +snapshot if another client deletes and recreates the same key during that read. +There is no load-time retry or duplicate identity read. Managed writes still +check the loaded creation identity and applied policy before saving. diff --git a/makefile b/makefile index a491ed2e..c1ce7b3a 100644 --- a/makefile +++ b/makefile @@ -58,7 +58,7 @@ docs: $(MAKE) -C docs/ html unittests: - python -m unittest discover tests + python -m pytest tests clean: rm -f dist/* diff --git a/redbeat/schedulers.py b/redbeat/schedulers.py index 12ee77bb..cfd9da4a 100644 --- a/redbeat/schedulers.py +++ b/redbeat/schedulers.py @@ -7,8 +7,9 @@ import json import ssl import warnings -from datetime import MINYEAR, datetime +from datetime import MINYEAR, datetime, timedelta, timezone from typing import Any +from uuid import uuid4 import redis.exceptions from celery.app import app_or_default @@ -20,7 +21,13 @@ from kombu.utils.url import maybe_sanitize_url from redis import Redis from redis.sentinel import MasterNotFoundError, Sentinel -from tenacity import retry, retry_if_exception_type, stop_after_delay, wait_exponential +from tenacity import ( + retry, + retry_if_exception_type, + stop_after_attempt, + stop_after_delay, + wait_exponential, +) from .decoder import RedBeatJSONDecoder, RedBeatJSONEncoder, to_timestamp @@ -55,6 +62,22 @@ REDBEAT_REDIS_KEY = "redbeat_redis" REDBEAT_SENTINEL_KEY = "redbeat_sentinel" +# Use three attempts in total for Redis write conflicts. +# Policy changes are raised separately so the caller can reload the entry. +_retry_watch_conflicts = retry( + retry=retry_if_exception_type(redis.exceptions.WatchError), + stop=stop_after_attempt(3), + reraise=True, +) + + +class EntryPolicyChanged(ValueError): + """The saved schedule has a different applied policy.""" + + +class EntryAlreadyExists(ValueError): + """Creation cannot replace an existing schedule hash.""" + class RetryingConnection: """A proxy for the Redis connection that delegates all the calls to @@ -306,6 +329,9 @@ def __init__( options=None, target=None, run_immediately=False, + jitter_fingerprint=None, + first_run_kwargs=None, + entry_id=None, **clsargs, ): super().__init__( @@ -320,6 +346,9 @@ def __init__( self.run_immediately = str(run_immediately) self.enabled = str(enabled) self.target = target + self.jitter_fingerprint = jitter_fingerprint + self.first_run_kwargs = dict(first_run_kwargs or {}) + self.entry_id = entry_id ensure_conf(self.app) @staticmethod @@ -338,6 +367,10 @@ def load_definition(key, app=None, definition=None): def decode_definition(definition): return json.loads(definition, cls=RedBeatJSONDecoder) + @staticmethod + def decode_json(value): + return json.loads(value) if value else None + @staticmethod def load_meta(key, app=None): return RedBeatSchedulerEntry.decode_meta(get_redis(app).hget(key, 'meta')) @@ -359,7 +392,11 @@ def from_key(cls, key, app=None): with get_redis(app).pipeline() as pipe: pipe.hget(key, 'definition') pipe.hget(key, 'meta') - definition, meta = pipe.execute() + pipe.hget(key, 'jitter_fingerprint') + pipe.hget(key, 'entry_id') + definition, meta, fingerprint, entry_id = pipe.execute() + entry_id = cls.decode_json(entry_id) + fingerprint = cls.decode_json(fingerprint) if not definition: raise KeyError(key) @@ -368,7 +405,13 @@ def from_key(cls, key, app=None): meta = cls.decode_meta(meta) definition.update(meta) - entry = cls(app=app, **definition) + # Keep the policy marker and creation identity outside the task definition. + entry = cls( + app=app, + jitter_fingerprint=fingerprint, + entry_id=entry_id, + **definition, + ) # celery.ScheduleEntry sets last_run_at = utcnow(), which is confusing and wrong entry.last_run_at = meta['last_run_at'] @@ -462,14 +505,20 @@ def save(self): meta = { 'last_run_at': self.last_run_at, } + if self.first_run_kwargs: + definition['first_run_kwargs'] = dict(self.first_run_kwargs) + immediate = self._strtobool(self.run_immediately) with get_redis(self.app).pipeline() as pipe: pipe.hset(self.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder)) pipe.hsetnx(self.key, 'meta', json.dumps(meta, cls=RedBeatJSONEncoder)) pipe.zadd(self.app.redbeat_conf.schedule_key, {self.key: self.score}) - if self._strtobool(self.run_immediately): + if immediate: + # An ordinary immediate save must not inherit a delayed policy. + pipe.hdel(self.key, 'jitter_fingerprint') pipe.sadd("run_immediately", self.key) pipe.execute() - + if immediate: + self.jitter_fingerprint = None return self def delete(self): @@ -478,6 +527,324 @@ def delete(self): pipe.delete(self.key) pipe.execute() + def _check_policy(self, fingerprint): + # Another writer may have changed the settings after this entry was read. + # Ask the caller to reload rather than save using the older settings. + if fingerprint != self.jitter_fingerprint: + raise EntryPolicyChanged('The applied jitter policy changed') + + def _check_entry(self, entry_id): + # Reject an older copy after deletion and creation under the same name. + if self.decode_json(entry_id) != self.entry_id: + raise KeyError(self.key) + + @_retry_watch_conflicts + def save_guarded(self, *, create=False): + """ + Save a loaded ordinary entry without overwriting a new managed policy. + + Like save(), this writes the caller's definition and due score while + retaining existing metadata. It also checks the loaded identity and + policy before writing, so a caller can reload after a policy change. + Creation requires an absent hash and assigns a new identity. Updating + a legacy entry without an identity does not add one. + + :param create: Whether to create an absent ordinary entry + + :return: Freshly loaded saved entry + :raises KeyError: If the schedule is missing or its creation identity changed + :raises ValueError: If the entry is managed + :raises EntryAlreadyExists: If creation finds an existing hash + :raises EntryPolicyChanged: If the saved entry acquired another policy + """ + with get_redis(self.app).pipeline(transaction=True) as pipe: + pipe.watch(self.key) + definition = pipe.hget(self.key, 'definition') + fingerprint = self.decode_json(pipe.hget(self.key, 'jitter_fingerprint')) + entry_id = pipe.hget(self.key, 'entry_id') + if create: + if pipe.exists(self.key): + raise EntryAlreadyExists('Cannot replace an existing schedule hash') + entry_id = str(uuid4()) + else: + if not definition: + raise KeyError(self.key) + self._check_entry(entry_id) + # Beat may have enabled jitter while this update was being prepared. + # Do not overwrite the new timing with the older copy. + self._check_policy(fingerprint) + if fingerprint: + raise ValueError('Managed entries require their guarded update operation') + definition = self._jitter_definition() + if self.first_run_kwargs: + definition['first_run_kwargs'] = dict(self.first_run_kwargs) + meta = {'last_run_at': self.last_run_at} + pipe.multi() + pipe.hset(self.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder)) + pipe.hsetnx(self.key, 'meta', json.dumps(meta, cls=RedBeatJSONEncoder)) + if create: + pipe.hset(self.key, 'entry_id', json.dumps(entry_id)) + pipe.zadd(self.app.redbeat_conf.schedule_key, {self.key: self.score}) + if self._strtobool(self.run_immediately): + pipe.sadd('run_immediately', self.key) + pipe.execute() + if create: + self.entry_id = entry_id + return type(self).from_key(self.key, app=self.app) + + def _jitter_definition(self): + """ + Build the base definition for exact creation and payload updates. + + :return: Recurring definition without pending first-run arguments + """ + return { + 'name': self.name, + 'task': self.task, + 'args': self.args, + 'kwargs': dict(self.kwargs), + 'options': self.options, + 'schedule': self.schedule, + 'enabled': self.enabled, + 'run_immediately': self.run_immediately, + } + + def _validate_due_time(self, due): + """ + Check an explicit interval deadline and normalize it to UTC. + + These operations represent the deadline as last_run_at plus one interval. + Calendar and relative schedules cannot use that calculation. Metadata + retains microseconds while the schedule index uses whole seconds. + + :param due: Requested timezone-aware datetime + + :return: The same instant in UTC, retaining microseconds + :raises ValueError: If the interval or due time is unsupported + """ + interval = getattr(self.schedule, 'run_every', None) + if ( + not isinstance(interval, timedelta) + or interval <= timedelta(0) + or getattr(self.schedule, 'relative', False) + ): + raise ValueError('Explicit timing requires a positive non-relative interval') + if not isinstance(due, datetime) or due.utcoffset() is None: + raise ValueError('Due time must be a timezone-aware datetime') + # Subtract intervals in UTC so a local daylight-saving change cannot + # move the requested instant. The existing encoder keeps microseconds. + return due.astimezone(timezone.utc) + + @_retry_watch_conflicts + def save_with_first_due(self, first_due, fingerprint, *, first_run_kwargs=None): + """ + Create a phased interval entry with its exact first due time. + + Definition, run metadata, due score, and fingerprint are saved together. + First-run arguments override matching recurring kwargs in the first + outgoing invocation. An existing hash is refused so creation cannot + overwrite another entry or a previously accepted run. Use request_run() + to change an existing managed entry's deadline. + Redis write conflicts allow three total attempts, at most two retries. + + :param first_due: Timezone-aware first due time, normalized to UTC + :param fingerprint: Nonempty identifier for the application's scheduling policy + :param first_run_kwargs: Arguments overlaid on the first outgoing invocation. + None uses this entry's pending arguments. An empty dict omits them. + Recurring kwargs remain unchanged. The published message contains the + overlaid arguments, so a task retry can reuse them. + + :return: This entry with its initial run metadata set + :raises ValueError: If timing or fingerprint is invalid + :raises EntryAlreadyExists: If creation finds an existing hash + """ + first_run_kwargs = dict( + self.first_run_kwargs if first_run_kwargs is None else first_run_kwargs + ) + if not isinstance(fingerprint, str) or not fingerprint: + raise ValueError('A jitter fingerprint is required') + first_due = self._validate_due_time(first_due) + definition = self._jitter_definition() + # Guarded writes compare this identity to reject older copies after + # recreation, even when the name, timing and payload are unchanged. + entry_id = str(uuid4()) + if first_run_kwargs: + definition['first_run_kwargs'] = first_run_kwargs + definition['run_immediately'] = 'False' + # For a 60s interval due at 12:01:20, save last_run_at as 12:00:20. + # This produces the chosen due without recording an actual execution. + meta = { + 'last_run_at': first_due - self.schedule.run_every, + 'total_run_count': self.total_run_count, + } + with get_redis(self.app).pipeline(transaction=True) as pipe: + pipe.watch(self.key) + if pipe.exists(self.key): + raise EntryAlreadyExists('Cannot replace an existing schedule hash') + # Save the chosen first time and matching run information together. + # Ordinary save() can calculate a different first time. + pipe.multi() + pipe.hset(self.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder)) + pipe.hset(self.key, 'meta', json.dumps(meta, cls=RedBeatJSONEncoder)) + pipe.hset(self.key, 'jitter_fingerprint', json.dumps(fingerprint)) + pipe.hset(self.key, 'entry_id', json.dumps(entry_id)) + pipe.zadd(self.app.redbeat_conf.schedule_key, {self.key: to_timestamp(first_due)}) + # Wait for the chosen first time instead of running immediately. + pipe.srem('run_immediately', self.key) + pipe.execute() + self.last_run_at = first_due - self.schedule.run_every + self.run_immediately = 'False' + self.jitter_fingerprint = fingerprint + self.first_run_kwargs = first_run_kwargs + self.entry_id = entry_id + return self + + @_retry_watch_conflicts + def request_run( + self, due, *, run_immediately=False, fingerprint=None, preserve_first_run_kwargs=False + ): + """ + Request a managed run using the earliest pending request deadline. + + Repeated delayed requests keep the earliest due and latest payload. + To request an urgent run, pass the current time as due. A later request + cannot postpone it, though the latest request still supplies the payload. + The existing immediate flag marks an accepted managed request. Its + interval anchor stores the deadline, which is checked before dispatch. + This temporary anchor is not an actual reservation timestamp. The run + count is preserved. + First-invocation arguments are cleared by default. A refresh can preserve + arguments still waiting in Redis without restoring arguments already + consumed by a reservation. Its accepted first deadline is also preserved. + Identical deadlines and payloads may coalesce into one invocation. + Redis write conflicts allow three total attempts, at most two retries. + + :param due: Timezone-aware requested due time, normalized to UTC + :param run_immediately: Whether to prompt immediate selection even for a + future deadline. Due or overdue requests always prompt selection. + This flag does not bypass the due-time check. + :param fingerprint: Applied policy after an intentional interval change + :param preserve_first_run_kwargs: Keep stored, unconsumed first-invocation + arguments and do not postpone their accepted deadline + + :return: This entry with its accepted deadline and updated definition + :raises KeyError: If the schedule is missing or its creation identity changed + :raises ValueError: If timing, interval or applied policy is invalid + """ + due = self._validate_due_time(due) + run_immediately = self._strtobool(run_immediately) + applied_fingerprint = self.jitter_fingerprint if fingerprint is None else fingerprint + if not isinstance(applied_fingerprint, str) or not applied_fingerprint: + raise ValueError('A jitter fingerprint is required') + + with get_redis(self.app).pipeline(transaction=True) as pipe: + pipe.watch(self.key) + raw_definition = pipe.hget(self.key, 'definition') + current_fingerprint = self.decode_json(pipe.hget(self.key, 'jitter_fingerprint')) + raw_meta = pipe.hget(self.key, 'meta') + entry_id = pipe.hget(self.key, 'entry_id') + if not raw_definition: + raise KeyError(self.key) + current = self.decode_definition(raw_definition) + self._check_entry(entry_id) + self._check_policy(current_fingerprint) + if fingerprint is None and current['schedule'] != self.schedule: + raise ValueError('Changing a request interval requires its applied policy') + if not current_fingerprint: + raise ValueError('A managed update requires an applied jitter policy') + + current_meta = self.decode_meta(raw_meta) + # A caller may have read these arguments before the first reservation. + # Use Redis so a later refresh cannot restore already-consumed arguments. + first_run_kwargs = ( + dict(current.get('first_run_kwargs', {})) if preserve_first_run_kwargs else {} + ) + if first_run_kwargs or self._strtobool(current.get('run_immediately', 'False')): + # A refresh must not postpone accepted first work or another request. + # Read its due using the old interval before applying an interval edit. + accepted_due = current_meta['last_run_at'] + current['schedule'].run_every + due = min(due, accepted_due) + definition = self._jitter_definition() + if first_run_kwargs: + definition['first_run_kwargs'] = first_run_kwargs + # Mark this as a requested run and save when it should happen below. + # Reuse the existing fields rather than create a separate request record. + definition['run_immediately'] = 'True' + meta = { + 'last_run_at': due - self.schedule.run_every, + 'total_run_count': current_meta.get('total_run_count', 0), + } + pipe.multi() + pipe.hset(self.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder)) + pipe.hset(self.key, 'meta', json.dumps(meta, cls=RedBeatJSONEncoder)) + if applied_fingerprint != current_fingerprint: + pipe.hset(self.key, 'jitter_fingerprint', json.dumps(applied_fingerprint)) + pipe.zadd(self.app.redbeat_conf.schedule_key, {self.key: to_timestamp(due)}) + # Prompt selection for urgent or overdue requests. Every request + # also retains its deadline in the schedule index for later selection. + if run_immediately or due <= self._default_now(): + pipe.sadd('run_immediately', self.key) + else: + pipe.srem('run_immediately', self.key) + pipe.execute() + self.run_immediately = definition['run_immediately'] + self.first_run_kwargs = first_run_kwargs + self.jitter_fingerprint = applied_fingerprint + self.last_run_at = meta['last_run_at'] + self.total_run_count = meta['total_run_count'] + return self + + @_retry_watch_conflicts + def update_definition(self): + """ + Update a managed entry's payload without changing its saved timing. + + The immediate flag and pending first-invocation arguments remain as stored. + Metadata, fingerprint, due score, and immediate-set membership are + untouched. This operation does not request a run. A definition that + serializes identically to the stored JSON does not need another write. + Redis write conflicts allow three total attempts, at most two retries. + + :return: This entry after saving the updated definition + :raises KeyError: If the schedule is missing or its creation identity changed + :raises ValueError: If the interval or applied policy is incompatible + """ + with get_redis(self.app).pipeline(transaction=True) as pipe: + pipe.watch(self.key) + raw_definition = pipe.hget(self.key, 'definition') + fingerprint = self.decode_json(pipe.hget(self.key, 'jitter_fingerprint')) + entry_id = pipe.hget(self.key, 'entry_id') + if not raw_definition: + raise KeyError(self.key) + + current = self.decode_definition(raw_definition) + + self._check_entry(entry_id) + self._check_policy(fingerprint) + if current['schedule'] != self.schedule: + raise ValueError('A definition-only update cannot change the interval') + if not fingerprint: + raise ValueError('A managed update requires an applied jitter policy') + + first_run_kwargs = current.get('first_run_kwargs', {}) + definition = self._jitter_definition() + # A refresh may have been requested while this update was prepared. + # Keep that request and any arguments still waiting for their first run. + if first_run_kwargs: + definition['first_run_kwargs'] = dict(first_run_kwargs) + definition['run_immediately'] = current.get('run_immediately', 'False') + encoded_definition = json.dumps(definition, cls=RedBeatJSONEncoder) + # Compare JSON text so byte responses work and argument type changes are kept. + if encoded_definition != json.dumps(json.loads(raw_definition)): + pipe.multi() + pipe.hset(self.key, 'definition', encoded_definition) + pipe.execute() + self.kwargs = definition['kwargs'] + self.run_immediately = definition['run_immediately'] + self.first_run_kwargs = dict(first_run_kwargs) + + return self + def set_enable(self, enabled): self.enabled = enabled @@ -485,6 +852,22 @@ def set_run_immediately(self, run_immediately): self.run_immediately = run_immediately def _next_instance(self, last_run_at=None, only_update_last_run_at=False): + """ + Reserve one invocation without changing the stored recurring arguments. + + Entries with a policy marker or creation identity use guarded writes. + These reject changes to the loaded policy or run state and check pending + request payloads. An optional application policy selects the following + deadline and policy marker. Its proposal is stored with this reservation. + Unmarked entries without a proposal keep their existing write path. + + :param last_run_at: Reservation timestamp, or the application's current time + :param only_update_last_run_at: Whether to retain the previous run count + + :return: Outgoing entry, with first-run arguments overlaid for guarded entries + :raises KeyError: If a guarded entry is missing or its creation identity changed + :raises ValueError: If compared guarded state changed before reservation + """ entry = super()._next_instance(last_run_at=last_run_at) if only_update_last_run_at: @@ -495,7 +878,24 @@ def _next_instance(self, last_run_at=None, only_update_last_run_at=False): 'last_run_at': entry.last_run_at, 'total_run_count': entry.total_run_count, } - + policy = None if only_update_last_run_at else self.app.conf.get('redbeat_entry_policy') + + # Copy kwargs so the first-run overlay leaves the recurring dict unchanged. + if self.jitter_fingerprint or self.entry_id: + entry.kwargs = dict(entry.kwargs) + entry.kwargs.update(self.first_run_kwargs) + entry.first_run_kwargs = {} + entry.run_immediately = 'False' + self._save_phased_reservation(entry, meta, policy=policy) + return entry + + # Preview policy adoption for an unmarked entry. A proposal changes the + # following run while this invocation keeps its already-selected timing. + if policy and self._following_timing(entry, policy) is not None: + if self._save_phased_reservation(entry, meta, policy=policy): + return entry + + # If no special timing update applies, save the next run as before. with get_redis(self.app).pipeline() as pipe: pipe.hset(self.key, 'meta', json.dumps(meta, cls=RedBeatJSONEncoder)) pipe.zadd(self.app.redbeat_conf.schedule_key, {entry.key: entry.score}) @@ -505,6 +905,180 @@ def _next_instance(self, last_run_at=None, only_update_last_run_at=False): __next__ = next = _next_instance + def _following_timing(self, entry, policy): + """ + Ask the application for the next run's optional deadline and policy marker. + + None keeps ordinary recurrence. A pair selects an exact following due + and fingerprint. A None due changes only the fingerprint, and a None + fingerprint removes the applied policy. An exception or invalid proposal + is ignored, so the reservation uses ordinary recurrence. Unmarked entries + preview the policy before the guarded read. The callback must not change + scheduling state because it runs again under WATCH and may repeat after + a Redis write conflict. + + :param entry: Recurring definition with the prospective reservation time + :param policy: Application callback that does not change scheduling state + + :return: Validated due and fingerprint pair, or None + """ + try: + proposal = policy(entry) + if proposal is None: + return None + due, fingerprint = proposal + if due is not None: + due = self._validate_due_time(due) + if due <= entry.last_run_at: + raise ValueError('The following due must be after its reservation') + if fingerprint is not None and (not isinstance(fingerprint, str) or not fingerprint): + raise ValueError('A nonempty policy fingerprint is required') + return due, fingerprint + except Exception: + logger.exception('beat: Following-run policy failed for %s', self.name) + return None + + @_retry_watch_conflicts + def _save_phased_reservation(self, entry, meta, *, policy=None): + """ + Save a phased reservation without replacing a newer task definition. + + Read the latest payload before clearing consumed first-run state. An + unchanged definition is left untouched. A changed requested deadline + or payload rejects this stale reservation so a later selection can use + the newer request. Identical requests may coalesce. + Redis write conflicts allow three total attempts, at most two retries, + rereading the saved state each time. + Deleted entries are not recreated. Changed policy, interval and run + metadata are rejected. A stored creation identity also rejects a + replacement under the same name, even when its other fields match. + Legacy entries may omit both the fingerprint and creation identity. + A changed saved value rejects this selection rather than falling back + to an unchecked write. The next tick reloads the current entry. + + :param entry: Outgoing entry with this reservation's metadata + :param meta: Run metadata to store for this reservation + :param policy: Optional pure callback proposing the next deadline and policy + + :return: Whether a guarded reservation was stored + :raises KeyError: If the schedule is missing or its creation identity changed + :raises ValueError: If policy, interval, or run state is incompatible + :raises redis.exceptions.WatchError: If concurrent writes prevent saving + """ + with get_redis(self.app).pipeline(transaction=True) as pipe: + pipe.watch(self.key) + raw_definition = pipe.hget(self.key, 'definition') + fingerprint = self.decode_json(pipe.hget(self.key, 'jitter_fingerprint')) + raw_meta = pipe.hget(self.key, 'meta') + entry_id = pipe.hget(self.key, 'entry_id') + if not raw_definition: + raise KeyError(self.key) + + # Another writer may have updated the task while Beat prepared this run. + # Keep its newer task arguments instead of saving Beat's older copy. + definition = self.decode_definition(raw_definition) + self._check_entry(entry_id) + self._check_policy(fingerprint) + if definition['schedule'] != self.schedule or definition['task'] != self.task: + raise ValueError('The schedule task or interval changed before reservation') + + current_meta = self.decode_meta(raw_meta) + # Another reservation or refresh may have changed this run's timing. + # Do not save this older selection over the newer run information. + if ( + current_meta.get('last_run_at') != self.last_run_at + or current_meta.get('total_run_count', 0) != self.total_run_count + ): + raise ValueError('The schedule run state changed before reservation') + + if ( + not fingerprint + and not self.entry_id + and pipe.sismember('run_immediately', self.key) + ): + # An ordinary immediate request is still pending. Let the ordinary + # reservation path handle it before applying a following-run policy. + return False + + if (fingerprint or self.entry_id) and self._strtobool( + definition.get('run_immediately', 'False') + ): + # A newer refresh may carry different arguments from this selection. + # Compare both copies in the same saved format before accepting it. + requested_definition = self._jitter_definition() + if self.first_run_kwargs: + requested_definition['first_run_kwargs'] = self.first_run_kwargs + requested_definition = self.decode_definition( + json.dumps(requested_definition, cls=RedBeatJSONEncoder) + ) + current_request = dict(definition) + # reschedule() saves target, while ordinary save() omits it. + # Compare it when the stored request includes that field. + if 'target' in current_request: + requested_definition['target'] = self.target + if not fingerprint: + # Ordinary is_due() clears its local immediate flag. The + # saved request still belongs to this run when its payload + # and run information match. + requested_definition['run_immediately'] = current_request['run_immediately'] + for flag in ('enabled', 'run_immediately'): + requested_definition[flag] = self._strtobool(requested_definition.get(flag)) + current_request[flag] = self._strtobool(current_request.get(flag)) + if current_request != requested_definition: + raise ValueError('The requested payload changed before reservation') + # Remove the first-run arguments used by this run. If another writer + # saved different first-run arguments, leave them for their own run. + definition_changed = False + if self.first_run_kwargs and ( + definition.get('first_run_kwargs') == self.first_run_kwargs + ): + definition.pop('first_run_kwargs') + definition_changed = True + if definition.get('run_immediately') != 'False': + definition['run_immediately'] = 'False' + definition_changed = True + + proposal = None + if policy and not definition.get('first_run_kwargs'): + # Defer policy changes while newer first-run arguments remain. + # Once consumed, the policy can choose the following deadline. + following = type(self)( + app=self.app, + jitter_fingerprint=fingerprint, + entry_id=self.entry_id, + **definition, + **meta, + ) + proposal = self._following_timing(following, policy) + if not fingerprint and not self.entry_id and proposal is None: + return False + stored_meta = meta + next_score = entry.score + next_fingerprint = fingerprint + if proposal is not None: + due, next_fingerprint = proposal + if due is not None: + # Keep the precise deadline in the interval anchor. Beat's + # whole-second index may select it before is_due() allows a run. + stored_meta = dict(meta, last_run_at=due - self.schedule.run_every) + next_score = to_timestamp(due) + + pipe.multi() + pipe.hset(self.key, 'meta', json.dumps(stored_meta, cls=RedBeatJSONEncoder)) + # Rewrite the definition only when consuming first-run arguments or + # normalizing the immediate flag, so ordinary runs avoid this write. + if definition_changed: + pipe.hset(self.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder)) + if next_fingerprint != fingerprint: + if next_fingerprint is None: + pipe.hdel(self.key, 'jitter_fingerprint') + else: + pipe.hset(self.key, 'jitter_fingerprint', json.dumps(next_fingerprint)) + pipe.zadd(self.app.redbeat_conf.schedule_key, {entry.key: next_score}) + pipe.srem('run_immediately', self.key) + pipe.execute() + return True + def reschedule(self, last_run_at=None): self.last_run_at = last_run_at or self._default_now() meta = { @@ -521,18 +1095,35 @@ def reschedule(self, last_run_at=None): 'enabled': self.enabled, 'run_immediately': self.run_immediately, } + if self.first_run_kwargs: + definition['first_run_kwargs'] = dict(self.first_run_kwargs) + immediate = self._strtobool(self.run_immediately) with get_redis(self.app).pipeline() as pipe: pipe.hset(self.key, 'meta', json.dumps(meta, cls=RedBeatJSONEncoder)) pipe.hset(self.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder)) pipe.zadd(self.app.redbeat_conf.schedule_key, {self.key: self.score}) - if self._strtobool(self.run_immediately): + if immediate: + # Keep legacy immediate rescheduling for a previously phased entry. + pipe.hdel(self.key, 'jitter_fingerprint') pipe.sadd("run_immediately", self.key) pipe.execute() + if immediate: + self.jitter_fingerprint = None def is_due(self): if not self._strtobool(self.enabled): return False, 5.0 # 5 second delay for re-enable. + if self.jitter_fingerprint and self._strtobool(self.run_immediately): + # Managed requests use run_immediately as a pending-request marker, + # including refreshes with a future deadline. Lookahead can select + # them early, so check the saved deadline before allowing dispatch. + # Urgent requests with a due-now deadline pass this check immediately. + remaining = ( + self.last_run_at + self.schedule.run_every - self._default_now() + ).total_seconds() + return remaining <= 0, remaining if remaining > 0 else self.schedule.seconds + if self._strtobool(self.run_immediately): self.run_immediately = False return True, self.schedule.seconds diff --git a/requirements-dev.txt b/requirements-dev.txt index ff5c5e07..62e0227c 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -14,5 +14,6 @@ flake8-isort # Testing fakeredis>=2.27.0 +pytest>=8 pbr diff --git a/tests/test_cluster_managed_integration.py b/tests/test_cluster_managed_integration.py new file mode 100644 index 00000000..63b19930 --- /dev/null +++ b/tests/test_cluster_managed_integration.py @@ -0,0 +1,582 @@ +import json +import os +import shutil +import socket +import subprocess +import time +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from unittest.mock import patch +from uuid import uuid4 + +import pytest +import redis +from celery import Celery +from celery.schedules import schedule +from redis import Redis +from redis.exceptions import ConnectionError + +from redbeat.decoder import RedBeatJSONEncoder, to_timestamp +from redbeat.schedulers import ( + EntryAlreadyExists, + RedBeatScheduler, + RedBeatSchedulerEntry, + RetryingConnection, +) + +NOW = datetime(2026, 1, 1, 12, tzinfo=timezone.utc) +POLICY = 'library-policy-one' + + +@dataclass(repr=False) +class ClusterNodes: + clients: list + ports: list + password: str + + +def reserve_node_ports(): + while True: + command_socket = socket.socket() + command_socket.bind(('127.0.0.1', 0)) + port = command_socket.getsockname()[1] + if port > 55535: + command_socket.close() + continue + bus_socket = socket.socket() + try: + bus_socket.bind(('127.0.0.1', port + 10000)) + except OSError: + command_socket.close() + bus_socket.close() + continue + return port, (command_socket, bus_socket) + + +@pytest.fixture(scope='module') +def cluster_nodes(tmp_path_factory): + executable = os.environ.get('REDBEAT_TEST_REDIS_SERVER') + if not executable: + pytest.skip('Set REDBEAT_TEST_REDIS_SERVER to an isolated Redis test binary') + if tuple(int(part) for part in redis.__version__.split('.')[:2]) < (6, 1): + pytest.skip('Managed Cluster transactions require redis-py 6.1 or later') + executable = shutil.which(executable) + if not executable: + pytest.fail('The requested Redis test binary is unavailable') + directory = tmp_path_factory.mktemp('managed-cluster') + password = uuid4().hex + processes = [] + clients = [] + ports = [] + try: + for index in range(3): + node_directory = directory / str(index) + node_directory.mkdir() + port, reservations = reserve_node_ports() + for reservation in reservations: + reservation.close() + process = subprocess.Popen( + [executable, '-'], + cwd=node_directory, + stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, + stderr=subprocess.STDOUT, + text=True, + ) + processes.append(process) + process.stdin.write( + '\n'.join( + [ + 'bind 127.0.0.1', + f'port {port}', + 'protected-mode yes', + f'requirepass {password}', + f'masterauth {password}', + 'cluster-enabled yes', + 'cluster-config-file nodes.conf', + 'cluster-node-timeout 1000', + 'cluster-announce-ip 127.0.0.1', + f'cluster-announce-port {port}', + f'cluster-announce-bus-port {port + 10000}', + 'save ""', + 'appendonly no', + f'dir {json.dumps(str(node_directory))}', + '', + ] + ) + ) + process.stdin.close() + client = Redis( + host='127.0.0.1', + port=port, + password=password, + socket_timeout=1, + decode_responses=True, + ) + clients.append(client) + ports.append(port) + deadline = time.monotonic() + 5 + while True: + if process.poll() is not None: + pytest.fail('An isolated Cluster node exited before startup') + try: + client.ping() + break + except ConnectionError: + if time.monotonic() >= deadline: + pytest.fail('An isolated Cluster node did not become ready') + time.sleep(0.02) + client.cluster('SET-CONFIG-EPOCH', index + 1) + start = index * 16384 // 3 + end = (index + 1) * 16384 // 3 + client.cluster('ADDSLOTS', *range(start, end)) + for port in ports[1:]: + clients[0].cluster('MEET', '127.0.0.1', port) + deadline = time.monotonic() + 10 + while not all(client.cluster('INFO')['cluster_state'] == 'ok' for client in clients): + if time.monotonic() >= deadline: + pytest.fail('The isolated Cluster did not cover all slots') + time.sleep(0.05) + yield ClusterNodes(clients, ports, password) + finally: + for client in clients: + client.close() + for process in processes: + if process.poll() is None: + process.terminate() + for process in processes: + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + +@pytest.fixture(params=[True, False], ids=['text', 'bytes']) +def cluster_app(cluster_nodes, request): + from redis.cluster import ClusterNode, RedisCluster + + nodes = cluster_nodes.clients + ports = cluster_nodes.ports + password = cluster_nodes.password + client = RedisCluster( + startup_nodes=[ClusterNode('127.0.0.1', port) for port in ports], + password=password, + decode_responses=request.param, + socket_timeout=2, + ) + app = Celery('managed-cluster-tests', broker='memory://', set_as_current=False) + app.conf.update( + redbeat_redis_url='redis://unused/0', + redbeat_key_prefix='{run_immediately}:tests:' + uuid4().hex + ':', + task_default_queue='managed-cluster-' + uuid4().hex, + timezone='UTC', + ) + app.redbeat_redis = client + app.now = lambda: NOW + try: + yield app + finally: + app.close() + client.close() + for node in nodes: + node.flushdb() + + +def create_entry(app, due=NOW, **kwargs): + return RedBeatSchedulerEntry( + 'managed-entry', 'tasks.example', schedule(60, app=app), app=app, **kwargs + ).save_with_first_due(due, POLICY) + + +def load(entry): + return RedBeatSchedulerEntry.from_key(entry.key, app=entry.app) + + +def stored_state(entry): + client = entry.app.redbeat_redis + return ( + client.hgetall(entry.key), + client.zscore(entry.app.redbeat_conf.schedule_key, entry.key), + client.sismember('run_immediately', entry.key), + ) + + +@pytest.mark.parametrize('writer', ['save', 'reschedule']) +def test_cluster_legacy_immediate_write_replaces_managed_timing(cluster_app, writer): + entry = create_entry(cluster_app, NOW + timedelta(seconds=20)) + identity = entry.entry_id + entry.run_immediately = True + getattr(entry, writer)() + stored = load(entry) + assert stored.jitter_fingerprint is None + assert stored.entry_id == identity + assert stored.is_due()[0] + next(stored) + assert load(entry).last_run_at == NOW + assert load(entry).total_run_count == 1 + + +def test_cluster_managed_creation_payload_refresh_and_reservation(cluster_app): + app = cluster_app + due = NOW + timedelta(seconds=20) + entry = create_entry( + app, + due, + kwargs={'value': 'original'}, + first_run_kwargs={'initial_only': True}, + ) + loaded = load(entry) + assert loaded.jitter_fingerprint == POLICY + assert json.loads(app.redbeat_redis.hget(entry.key, 'jitter_fingerprint')) == POLICY + assert loaded.last_run_at == due - timedelta(seconds=60) + before = stored_state(loaded) + loaded.kwargs['value'] = 'updated' + loaded.update_definition() + assert stored_state(loaded)[1:] == before[1:] + app.now = lambda: due + outgoing = next(load(entry)) + assert outgoing.kwargs == {'value': 'updated', 'initial_only': True} + saved = load(entry) + assert saved.kwargs == {'value': 'updated'} + assert saved.first_run_kwargs == {} + assert saved.total_run_count == 1 + assert stored_state(saved)[1] == to_timestamp(due + timedelta(seconds=60)) + + requested = due + timedelta(seconds=15) + saved.request_run(requested) + assert not app.redbeat_redis.sismember('run_immediately', entry.key) + load(entry).request_run(requested + timedelta(seconds=10)) + assert stored_state(entry)[1] == to_timestamp(requested) + app.now = lambda: due + timedelta(seconds=1) + load(entry).request_run(app.now(), run_immediately=True) + assert app.redbeat_redis.sismember('run_immediately', entry.key) + urgent = load(entry) + assert urgent.is_due()[0] + next(urgent) + assert load(entry).total_run_count == 2 + assert not app.redbeat_redis.sismember('run_immediately', entry.key) + assert stored_state(entry)[1] == to_timestamp(app.now() + timedelta(seconds=60)) + entry.delete() + assert stored_state(entry) == ({}, None, False) + + +def test_cluster_guarded_ordinary_update(cluster_app): + entry = RedBeatSchedulerEntry( + 'ordinary-entry', 'tasks.example', schedule(60, app=cluster_app), app=cluster_app + ).save() + entry.kwargs = {'updated': True} + updated = entry.save_guarded() + assert updated.kwargs == {'updated': True} + assert updated.jitter_fingerprint is None + + +@pytest.mark.parametrize('phased', [False, True]) +def test_cluster_creation_conflict_preserves_winner_and_unset_caller_identity(cluster_app, phased): + app = cluster_app + entry = RedBeatSchedulerEntry('creation-race', 'tasks.example', schedule(60, app=app), app=app) + pipeline_class = type(app.redbeat_redis.pipeline(transaction=True)) + execute = pipeline_class.execute + winner = [] + winner_state = [] + + def commit(pipe, *args, **kwargs): + if not winner: + replacement = RedBeatSchedulerEntry( + entry.name, entry.task, entry.schedule, app=app, kwargs={'payload': 'winner'} + ) + winner.append(replacement) + replacement.save_guarded(create=True) + winner_state.append(stored_state(replacement)) + return execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', commit): + with pytest.raises(EntryAlreadyExists): + if phased: + entry.save_with_first_due(NOW, POLICY) + else: + entry.save_guarded(create=True) + assert entry.entry_id is None + assert stored_state(entry) == winner_state[0] + assert load(entry).entry_id == winner[0].entry_id + + +@pytest.mark.parametrize('operation', ['definition', 'request', 'reservation', 'ordinary']) +def test_cluster_creation_identity_rejects_same_key_replacement(cluster_app, operation): + app = cluster_app + if operation == 'ordinary': + stale = RedBeatSchedulerEntry( + 'managed-entry', 'tasks.example', schedule(60, app=app), app=app + ).save_guarded(create=True) + else: + stale = create_entry(app) + stale.delete() + if operation == 'ordinary': + replacement = RedBeatSchedulerEntry( + stale.name, 'tasks.example', schedule(60, app=app), app=app + ).save_guarded(create=True) + else: + replacement = create_entry(app) + assert load(replacement).entry_id == replacement.entry_id + assert stale.entry_id != replacement.entry_id + before = stored_state(replacement) + with pytest.raises(KeyError): + if operation == 'definition': + stale.update_definition() + elif operation == 'request': + stale.request_run(NOW) + elif operation == 'ordinary': + stale.save_guarded() + else: + next(stale) + assert stored_state(replacement) == before + + +def test_cluster_default_prefix_ordinary_path_remains_usable(cluster_app): + app = cluster_app + app.conf.redbeat_key_prefix = 'redbeat:' + entry = RedBeatSchedulerEntry( + 'ordinary-entry', 'tasks.example', schedule(60, app=app), app=app + ).save() + assert load(entry).jitter_fingerprint is None + next(load(entry)) + assert load(entry).total_run_count == 1 + entry.reschedule(NOW + timedelta(seconds=1)) + assert load(entry).last_run_at == NOW + timedelta(seconds=1) + entry.delete() + assert stored_state(entry) == ({}, None, False) + + +@pytest.mark.parametrize('operation', ['create', 'ordinary-update', 'request', 'reserve']) +def test_cluster_cross_slot_timing_write_leaves_state_unchanged(cluster_app, operation): + from redis.exceptions import RedisClusterException + + app = cluster_app + app.conf.redbeat_key_prefix = 'redbeat:' + entry = RedBeatSchedulerEntry( + 'cross-slot-entry', 'tasks.example', schedule(60, app=app), app=app + ) + if operation != 'create': + entry.save() + if operation != 'ordinary-update': + app.redbeat_redis.hset(entry.key, 'jitter_fingerprint', json.dumps(POLICY)) + entry = load(entry) + before = stored_state(entry) + with pytest.raises(RedisClusterException): + if operation == 'create': + entry.save_with_first_due(NOW + timedelta(seconds=20), POLICY) + elif operation == 'ordinary-update': + entry.kwargs = {'new': True} + entry.save_guarded() + elif operation == 'request': + entry.request_run(NOW + timedelta(seconds=20)) + else: + next(entry) + assert stored_state(entry) == before + + +def test_cluster_single_hash_definition_update_needs_no_shared_tag(cluster_app): + app = cluster_app + app.conf.redbeat_key_prefix = 'redbeat:' + entry = RedBeatSchedulerEntry( + 'single-hash-entry', 'tasks.example', schedule(60, app=app), app=app + ).save() + app.redbeat_redis.hset(entry.key, 'jitter_fingerprint', json.dumps(POLICY)) + entry = load(entry) + before = stored_state(entry) + entry.kwargs = {'updated': True} + entry.update_definition() + assert load(entry).kwargs == {'updated': True} + assert stored_state(entry)[1:] == before[1:] + pipeline_class = type(app.redbeat_redis.pipeline(transaction=True)) + with patch.object(pipeline_class, 'execute') as execute: + entry.update_definition() + execute.assert_not_called() + + +def test_cluster_definition_update_retries_a_real_watch_conflict(cluster_app): + app = cluster_app + entry = create_entry(app) + entry.kwargs = {'updated': True} + pipeline_class = type(app.redbeat_redis.pipeline(transaction=True)) + original_execute = pipeline_class.execute + attempts = [] + + def conflict_once(pipe, *args, **kwargs): + attempts.append(True) + if len(attempts) == 1: + app.redbeat_redis.hset( + entry.key, + 'meta', + json.dumps({'last_run_at': NOW, 'total_run_count': 7}, cls=RedBeatJSONEncoder), + ) + return original_execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', conflict_once): + entry.update_definition() + assert len(attempts) == 2 + assert load(entry).kwargs == {'updated': True} + assert load(entry).total_run_count == 7 + + +def test_cluster_reservation_retries_without_replacing_new_payload(cluster_app): + app = cluster_app + entry = create_entry(app, kwargs={'value': 'original'}) + pipeline_class = type(app.redbeat_redis.pipeline(transaction=True)) + original_execute = pipeline_class.execute + attempts = [] + + def conflict_once(pipe, *args, **kwargs): + attempts.append(True) + if len(attempts) == 1: + definition = json.loads(app.redbeat_redis.hget(entry.key, 'definition')) + definition['kwargs'] = {'value': 'newer'} + app.redbeat_redis.hset( + entry.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder) + ) + return original_execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', conflict_once): + outgoing = next(entry) + assert len(attempts) == 2 + assert outgoing.kwargs == {'value': 'original'} + assert load(entry).kwargs == {'value': 'newer'} + assert load(entry).total_run_count == 1 + + +def test_cluster_reservation_rejects_a_newer_run(cluster_app): + entry = create_entry(cluster_app) + stale = load(entry) + next(entry) + before = stored_state(entry) + with pytest.raises(ValueError, match='run state'): + next(stale) + assert stored_state(entry) == before + + +def test_cluster_generic_policy_changes_only_the_following_run(cluster_app): + app = cluster_app + due = NOW + timedelta(seconds=20) + entry = create_entry(app, due) + calls = [] + + def policy(following): + calls.append(following.jitter_fingerprint) + if following.jitter_fingerprint == POLICY: + return following.last_run_at + timedelta(seconds=80), 'library-policy-two' + return None + + app.conf.redbeat_entry_policy = policy + scheduler = RedBeatScheduler(app, lazy=True, max_interval=3600) + try: + with app.connection_for_read() as connection: + queue = connection.SimpleQueue(app.conf.task_default_queue) + try: + app.now = lambda: due - timedelta(seconds=1) + scheduler.tick() + assert calls == [] + assert queue.qsize() == 0 + app.now = lambda: due + scheduler.tick() + message = queue.get(block=False) + message.ack() + assert queue.qsize() == 0 + assert calls == [POLICY] + assert load(entry).jitter_fingerprint == 'library-policy-two' + following_due = due + timedelta(seconds=80) + assert stored_state(entry)[1] == to_timestamp(following_due) + app.now = lambda: following_due + scheduler.tick() + message = queue.get(block=False) + message.ack() + assert load(entry).total_run_count == 2 + assert stored_state(entry)[1] == to_timestamp(following_due + timedelta(seconds=60)) + finally: + queue.close() + finally: + scheduler.close() + + +def test_cluster_retrying_connection_preserves_transaction_behavior(cluster_app): + app = cluster_app + app.redbeat_redis = RetryingConnection(0, app.redbeat_redis) + entry = create_entry(app) + loaded = load(entry) + loaded.kwargs = {'updated': True} + loaded.update_definition() + loaded.request_run(NOW + timedelta(seconds=10)) + app.now = lambda: NOW + timedelta(seconds=10) + next(load(entry)) + assert load(entry).total_run_count == 1 + assert load(entry).kwargs == {'updated': True} + + +def test_cluster_fractional_deadlines_preserve_precision_and_request_state(cluster_app): + app = cluster_app + local_zone = timezone(timedelta(hours=5.5)) + due = NOW + timedelta(microseconds=250000) + entry = RedBeatSchedulerEntry( + 'fractional-timing', 'tasks.example', schedule(1.5, app=app), app=app + ).save_with_first_due(due.astimezone(local_zone), POLICY) + scheduler = RedBeatScheduler(app, lazy=True, max_interval=60) + try: + with patch.object(app, 'send_task') as publish: + for count, deadline in enumerate((due, due + timedelta(seconds=0.8)), 1): + app.now = lambda: deadline - timedelta(microseconds=1) + scheduler.tick() + publish.assert_not_called() + app.now = lambda: deadline + scheduler.tick() + publish.assert_called_once() + publish.reset_mock() + assert load(entry).total_run_count == count + if count == 1: + load(entry).request_run((due + timedelta(seconds=0.8)).astimezone(local_zone)) + following_due = due + timedelta(seconds=3.3) + app.conf.redbeat_entry_policy = lambda following: ( + following_due.astimezone(local_zone), + 'library-policy-two', + ) + stored = load(entry) + assert stored.jitter_fingerprint == 'library-policy-two' + assert stored.last_run_at == following_due - timedelta(seconds=1.5) + assert stored.last_run_at.tzinfo == timezone.utc + assert stored_state(entry)[1] == to_timestamp(following_due) + finally: + scheduler.close() + + +def test_cluster_json_fingerprint_roundtrips_with_non_default_encoding(cluster_app, cluster_nodes): + from redis.cluster import ClusterNode, RedisCluster + + app = cluster_app + ports = cluster_nodes.ports + password = cluster_nodes.password + original = app.redbeat_redis + client = RedisCluster( + startup_nodes=[ClusterNode('127.0.0.1', port) for port in ports], + password=password, + encoding='latin-1', + decode_responses=original.get_encoder().decode_responses, + socket_timeout=2, + ) + app.redbeat_redis = client + try: + fingerprint = 'library-policy-caf\u00e9-\u03bb' + entry = RedBeatSchedulerEntry( + 'encoded-marker', 'tasks.example', schedule(60, app=app), app=app + ).save_with_first_due(NOW, fingerprint) + raw = client.hget(entry.key, 'jitter_fingerprint') + assert json.loads(raw) == fingerprint + current = load(entry) + assert current.jitter_fingerprint == fingerprint + current.kwargs = {'updated': True} + current.update_definition() + current.request_run(NOW + timedelta(seconds=10)) + app.now = lambda: NOW + timedelta(seconds=10) + next(load(entry)) + assert load(entry).jitter_fingerprint == fingerprint + assert load(entry).total_run_count == 1 + finally: + app.redbeat_redis = original + client.close() diff --git a/tests/test_entry_policy.py b/tests/test_entry_policy.py new file mode 100644 index 00000000..2839cf38 --- /dev/null +++ b/tests/test_entry_policy.py @@ -0,0 +1,367 @@ +from datetime import timedelta +from unittest.mock import Mock, patch + +import pytest +from celery.schedules import schedule +from redis.exceptions import WatchError + +from redbeat.schedulers import EntryPolicyChanged, RedBeatScheduler, RedBeatSchedulerEntry +from tests.test_jitter_concurrent_updates import app as policy_app +from tests.test_jitter_concurrent_updates import create_entry, load +from tests.test_jitter_integration import NOW +from tests.test_jitter_integration import app as redis_app # noqa: F401 + +app = policy_app + + +def score(entry): + return entry.app.redbeat_redis.zscore(entry.app.redbeat_conf.schedule_key, entry.key) + + +def legacy_entry(app, **kwargs): + return RedBeatSchedulerEntry( + 'ordinary-entry', 'tasks.test', schedule(60, app=app), app=app, **kwargs + ).save() + + +def phase_following(entry): + return entry.last_run_at + timedelta(seconds=80), 'policy-one' + + +def test_policy_preserves_current_due_and_runs_only_during_reservation(app): + entry = create_entry(app, NOW + timedelta(seconds=60)) + before = app.redbeat_redis.hgetall(entry.key) + callback = Mock(side_effect=phase_following) + app.conf.redbeat_entry_policy = callback + scheduler = RedBeatScheduler(app, lazy=True, max_interval=3600) + try: + with patch.object(app, 'send_task') as publish: + for instant in (NOW, NOW + timedelta(seconds=59, microseconds=999999)): + app.now = lambda: instant + scheduler.tick() + callback.assert_not_called() + publish.assert_not_called() + assert app.redbeat_redis.hgetall(entry.key) == before + assert score(entry) == (NOW + timedelta(seconds=60)).timestamp() + app.now = lambda: NOW + timedelta(seconds=60) + scheduler.tick() + publish.assert_called_once() + callback.assert_called_once() + assert score(entry) == (NOW + timedelta(seconds=140)).timestamp() + assert load(entry).total_run_count == 1 + finally: + scheduler.close() + + +@pytest.mark.parametrize('immediate', [False, True]) +def test_first_adoption_serves_current_ordinary_run_then_phases_following(app, immediate): + entry = legacy_entry(app, run_immediately=immediate, kwargs={'value': 'original'}) + app.conf.redbeat_entry_policy = phase_following + scheduler = RedBeatScheduler(app, lazy=True, max_interval=5) + try: + if not immediate: + app.now = lambda: NOW + timedelta(seconds=60) + with patch.object(app, 'send_task') as publish: + scheduler.tick() + publish.assert_called_once() + stored = load(entry) + assert stored.jitter_fingerprint == 'policy-one' + assert stored.kwargs == {'value': 'original'} + assert stored.total_run_count == 1 + assert stored.last_run_at == app.now() + timedelta(seconds=20) + assert score(entry) == (app.now() + timedelta(seconds=80)).timestamp() + assert not stored._strtobool(stored.run_immediately) + assert not app.redbeat_redis.sismember('run_immediately', entry.key) + finally: + scheduler.close() + + +def test_policy_sees_fresh_recurring_payload_and_actual_reservation_metadata(app): + entry = create_entry(app, kwargs={'value': 'old'}, first_run_kwargs={'bootstrap': 'first'}) + current = load(entry) + current.kwargs = {'value': 'new'} + current.args = ['latest'] + current.options = {'queue': 'latest-queue', 'expires': 120} + current.update_definition() + calls = [] + + def policy(following): + calls.append( + ( + dict(following.kwargs), + following.args, + following.last_run_at, + following.total_run_count, + dict(following.first_run_kwargs), + ) + ) + return phase_following(following) + + app.conf.redbeat_entry_policy = policy + outgoing = next(entry) + assert calls == [({'value': 'new'}, ['latest'], NOW, 1, {})] + assert outgoing.kwargs == {'value': 'old', 'bootstrap': 'first'} + assert outgoing.last_run_at == NOW + assert outgoing.total_run_count == 1 + assert load(entry).kwargs == {'value': 'new'} + assert load(entry).first_run_kwargs == {} + assert load(entry).last_run_at == NOW + timedelta(seconds=20) + + +@pytest.mark.parametrize('managed', [False, True]) +def test_no_proposal_keeps_normal_reservation_and_no_new_fields(app, managed): + entry = create_entry(app) if managed else legacy_entry(app) + callback = Mock(return_value=None) + app.conf.redbeat_entry_policy = callback + before = app.redbeat_redis.hget(entry.key, 'definition') + if managed: + outgoing = next(load(entry)) + else: + pipeline_class = type(app.redbeat_redis.pipeline()) + with patch.object(pipeline_class, 'watch') as watched: + outgoing = next(load(entry)) + watched.assert_not_called() + callback.assert_called_once() + assert outgoing.last_run_at == NOW + assert load(entry).last_run_at == NOW + assert load(entry).total_run_count == 1 + assert score(entry) == (NOW + timedelta(seconds=60)).timestamp() + assert app.redbeat_redis.hget(entry.key, 'definition') == before + assert set(app.redbeat_redis.hgetall(entry.key)) == ( + {'definition', 'meta', 'jitter_fingerprint', 'entry_id'} + if managed + else {'definition', 'meta'} + ) + + +def test_metadata_only_update_does_not_call_policy(app): + entry = create_entry(app) + callback = Mock(side_effect=phase_following) + app.conf.redbeat_entry_policy = callback + outgoing = entry.next(only_update_last_run_at=True) + callback.assert_not_called() + assert outgoing.total_run_count == load(entry).total_run_count == 0 + assert load(entry).last_run_at == NOW + + +@pytest.mark.parametrize('fingerprint', ['policy-two', None]) +def test_fingerprint_only_proposal_keeps_normal_following_due(app, fingerprint): + entry = create_entry(app) + app.conf.redbeat_entry_policy = lambda following: (None, fingerprint) + next(entry) + assert load(entry).jitter_fingerprint == fingerprint + assert load(entry).last_run_at == NOW + assert load(entry).total_run_count == 1 + assert score(entry) == (NOW + timedelta(seconds=60)).timestamp() + + +def test_disable_removes_policy_during_reservation_and_allows_ordinary_updates(app): + entry = create_entry(app) + app.conf.redbeat_entry_policy = lambda following: (NOW + timedelta(seconds=60), None) + next(entry) + updated = load(entry) + assert updated.jitter_fingerprint is None + app.conf.redbeat_entry_policy = None + updated.schedule = schedule(120, app=app) + updated.run_immediately = True + updated = updated.save_guarded() + assert updated.last_run_at == NOW + assert updated.total_run_count == 1 + assert updated.is_due()[0] + next(updated) + assert load(updated).total_run_count == 2 + assert score(updated) == (NOW + timedelta(seconds=120)).timestamp() + with pytest.raises(EntryPolicyChanged): + entry.update_definition() + + +def test_loaded_legacy_save_cannot_overwrite_first_policy_adoption(app): + stale = legacy_entry(app) + app.conf.redbeat_entry_policy = phase_following + next(load(stale)) + before = app.redbeat_redis.hgetall(stale.key) + stale.kwargs = {'value': 'new'} + with pytest.raises(EntryPolicyChanged): + stale.save_guarded() + assert app.redbeat_redis.hgetall(stale.key) == before + assert score(stale) == (NOW + timedelta(seconds=80)).timestamp() + + +@pytest.mark.parametrize('run_immediately', [False, True]) +def test_guarded_save_rejects_managed_pending_request_without_writes(app, run_immediately): + entry = create_entry(app, kwargs={'value': 'accepted'}) + entry.request_run(NOW + timedelta(seconds=20), run_immediately=run_immediately) + entry = load(entry) + before = (app.redbeat_redis.hgetall(entry.key), score(entry)) + entry.kwargs = {'value': 'rejected'} + with pytest.raises(ValueError, match='Managed entries require'): + entry.save_guarded() + assert (app.redbeat_redis.hgetall(entry.key), score(entry)) == before + + +@pytest.mark.parametrize('during_watch', [False, True]) +def test_first_adoption_keeps_new_ordinary_immediate_request(app, during_watch): + entry = legacy_entry(app, kwargs={'value': 'old'}) + current = load(entry) + calls = [] + + def policy(following): + calls.append(True) + if len(calls) == (2 if during_watch else 1): + current.kwargs = {'value': 'new'} + current.run_immediately = True + current.save_guarded() + return phase_following(following) + + app.conf.redbeat_entry_policy = policy + outgoing = next(entry) + stored = load(entry) + assert outgoing.kwargs == {'value': 'old'} + assert stored.kwargs == {'value': 'new'} + assert stored.jitter_fingerprint is None + assert stored._strtobool(stored.run_immediately) + assert app.redbeat_redis.sismember('run_immediately', entry.key) + scheduler = RedBeatScheduler(app, lazy=True, max_interval=1) + try: + with patch.object(app, 'send_task') as publish: + scheduler.tick() + publish.assert_called_once() + assert load(entry).jitter_fingerprint == 'policy-one' + assert not load(entry)._strtobool(load(entry).run_immediately) + finally: + scheduler.close() + + +def test_new_first_run_context_is_preserved_before_policy_adoption(app): + stale = create_entry(app, first_run_kwargs={'bootstrap': 'old'}) + current = load(stale) + current.first_run_kwargs = {'bootstrap': 'new'} + current.save() + callback = Mock(side_effect=phase_following) + app.conf.redbeat_entry_policy = callback + outgoing = next(stale) + callback.assert_not_called() + assert outgoing.kwargs == {'bootstrap': 'old'} + assert load(stale).first_run_kwargs == {'bootstrap': 'new'} + assert load(stale).jitter_fingerprint == stale.jitter_fingerprint + + +def test_policy_watch_retry_reads_latest_payload_without_changing_outgoing(app): + entry = create_entry(app, kwargs={'value': 'old'}) + current = load(entry) + calls = [] + + def policy(following): + calls.append(following.kwargs['value']) + if len(calls) == 1: + current.kwargs = {'value': 'new'} + current.update_definition() + return phase_following(following) + + app.conf.redbeat_entry_policy = policy + outgoing = next(entry) + assert calls == ['old', 'new'] + assert outgoing.kwargs == {'value': 'old'} + assert load(entry).kwargs == {'value': 'new'} + assert score(entry) == (NOW + timedelta(seconds=80)).timestamp() + + +def test_new_managed_request_during_policy_is_not_erased_or_published_stale(app): + entry = create_entry(app) + current = load(entry) + + def policy(following): + current.kwargs = {'value': 'accepted'} + current.request_run(NOW + timedelta(seconds=20)) + return phase_following(following) + + app.conf.redbeat_entry_policy = policy + scheduler = RedBeatScheduler(app, lazy=True, max_interval=1) + try: + with patch.object(app, 'send_task') as publish: + scheduler.tick() + publish.assert_not_called() + assert load(entry).total_run_count == 0 + assert load(entry).kwargs == {'value': 'accepted'} + assert load(entry)._strtobool(load(entry).run_immediately) + assert score(entry) == (NOW + timedelta(seconds=20)).timestamp() + finally: + scheduler.close() + + +@pytest.mark.parametrize('managed', [False, True]) +@pytest.mark.parametrize('failure', ['raises', 'shape', 'fingerprint', 'due', 'past', 'equal']) +def test_policy_failure_keeps_current_publication(app, managed, failure): + entry = create_entry(app) if managed else legacy_entry(app, run_immediately=True) + original_fingerprint = entry.jitter_fingerprint + + def policy(following): + if failure == 'raises': + raise ValueError('application policy failure') + if failure == 'shape': + return (NOW,) + if failure == 'fingerprint': + return NOW + timedelta(seconds=80), '' + if failure == 'past': + return NOW - timedelta(seconds=1), 'policy-two' + if failure == 'equal': + return NOW, 'policy-two' + return NOW.replace(tzinfo=None), 'policy-two' + + app.conf.redbeat_entry_policy = policy + scheduler = RedBeatScheduler(app, lazy=True, max_interval=1) + try: + with patch.object(app, 'send_task') as publish: + scheduler.tick() + publish.assert_called_once() + assert load(entry).total_run_count == 1 + assert load(entry).jitter_fingerprint == original_fingerprint + assert score(entry) == (NOW + timedelta(seconds=60)).timestamp() + finally: + scheduler.close() + + +def test_publish_failure_keeps_existing_reservation_boundary(app): + entry = create_entry(app) + app.conf.redbeat_entry_policy = phase_following + scheduler = RedBeatScheduler(app, lazy=True, max_interval=1) + try: + with patch.object( + app, 'send_task', side_effect=RuntimeError('broker unavailable') + ) as publish: + scheduler.tick() + publish.assert_called_once() + assert load(entry).total_run_count == 1 + assert load(entry).jitter_fingerprint == 'policy-one' + assert score(entry) == (NOW + timedelta(seconds=80)).timestamp() + finally: + scheduler.close() + + +@pytest.mark.parametrize('conflicts', [1, 3]) +def test_following_policy_commit_has_at_most_three_watch_attempts(app, conflicts): + entry = create_entry(app) + before = app.redbeat_redis.hgetall(entry.key) + before_score = score(entry) + app.conf.redbeat_entry_policy = phase_following + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + attempts = [] + + def conflict(pipe, *args, **kwargs): + if any(command[0][0] == 'ZADD' for command in pipe.command_stack): + attempts.append(True) + if len(attempts) <= conflicts: + raise WatchError('concurrent reservation') + return execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', conflict): + if conflicts == 3: + with pytest.raises(WatchError): + next(entry) + assert app.redbeat_redis.hgetall(entry.key) == before + assert score(entry) == before_score + else: + next(entry) + assert score(entry) == (NOW + timedelta(seconds=80)).timestamp() + assert len(attempts) == min(conflicts + 1, 3) diff --git a/tests/test_jitter_boundaries_integration.py b/tests/test_jitter_boundaries_integration.py new file mode 100644 index 00000000..bbd5c815 --- /dev/null +++ b/tests/test_jitter_boundaries_integration.py @@ -0,0 +1,175 @@ +from concurrent.futures import ThreadPoolExecutor +from datetime import timedelta +from threading import Barrier +from unittest.mock import patch + +import pytest +from celery.schedules import schedule +from redis.exceptions import WatchError + +from redbeat.schedulers import RedBeatScheduler, RedBeatSchedulerEntry +from tests.test_jitter_integration import FINGERPRINT, NOW +from tests.test_jitter_integration import app as redis_app +from tests.test_jitter_integration import read_message + +app = redis_app + + +def create_entry(app, interval=60, delay=20): + app.now = lambda: NOW + entry = RedBeatSchedulerEntry( + 'first-due-test', 'validation.noop', schedule(interval, app=app), app=app + ) + entry.save_with_first_due(NOW + timedelta(seconds=delay), FINGERPRINT) + return RedBeatSchedulerEntry.from_key(entry.key, app=app) + + +@pytest.mark.parametrize('interval', [1, 10, 60, 300, 301, 600, 1800, 86400]) +@pytest.mark.parametrize('delay', [1, 20, 600]) +def test_supplied_first_due_and_three_reservations(app, interval, delay): + entry = create_entry(app, interval, delay) + first = NOW + timedelta(seconds=delay) + assert entry.last_run_at == first - timedelta(seconds=interval) + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) == first.timestamp() + scheduler = RedBeatScheduler(app, lazy=True, max_interval=86400) + with app.connection_for_read() as connection: + queue = connection.SimpleQueue(app.conf.task_default_queue) + try: + for cycle in range(3): + due = first + timedelta(seconds=cycle * interval) + app.now = lambda: due - timedelta(microseconds=1) + scheduler.tick() + assert read_message(queue) is None + app.now = lambda: due + scheduler.tick() + message = read_message(queue) + assert message is not None + message.ack() + assert read_message(queue) is None + stored = RedBeatSchedulerEntry.from_key(entry.key, app=app) + assert stored.total_run_count == cycle + 1 + assert stored.jitter_fingerprint == FINGERPRINT + assert ( + app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + == (due + timedelta(seconds=interval)).timestamp() + ) + finally: + queue.close() + scheduler.close() + + +def test_long_outage_publishes_once_and_reanchors(app): + entry = create_entry(app, interval=10) + late = NOW + timedelta(hours=2) + app.now = lambda: late + scheduler = RedBeatScheduler(app, lazy=True) + with patch.object(app, 'send_task') as publish: + for _ in range(5): + scheduler.tick() + assert publish.call_count == 1 + assert RedBeatSchedulerEntry.from_key(entry.key, app=app).last_run_at == late + assert ( + app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + == (late + timedelta(seconds=10)).timestamp() + ) + + +def test_fractional_reservation_does_not_publish_early(app): + entry = create_entry(app, interval=10, delay=1) + late = NOW + timedelta(seconds=11, microseconds=900000) + app.now = lambda: late + scheduler = RedBeatScheduler(app, lazy=True) + with app.connection_for_read() as connection: + queue = connection.SimpleQueue(app.conf.task_default_queue) + try: + scheduler.tick() + message = read_message(queue) + assert message is not None + message.ack() + next_due = late + timedelta(seconds=10) + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) == int( + next_due.timestamp() + ) + app.now = lambda: next_due - timedelta(microseconds=1) + scheduler.tick() + assert read_message(queue) is None + app.now = lambda: next_due + scheduler.tick() + message = read_message(queue) + assert message is not None + message.ack() + finally: + queue.close() + scheduler.close() + + +@pytest.mark.parametrize('orphan', [False, True]) +def test_exact_creation_refuses_existing_hash_without_repair(app, orphan): + entry = create_entry(app) + if orphan: + app.redbeat_redis.hdel(entry.key, 'definition') + before = app.redbeat_redis.hgetall(entry.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + with pytest.raises(ValueError, match='existing schedule hash'): + entry.save_with_first_due(NOW + timedelta(seconds=900), entry.jitter_fingerprint) + assert app.redbeat_redis.hgetall(entry.key) == before + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) == score + + +def test_publication_failure_keeps_existing_reservation_boundary(app): + entry = create_entry(app) + due = NOW + timedelta(seconds=20) + app.now = lambda: due + scheduler = RedBeatScheduler(app, lazy=True) + with patch.object(app, 'send_task', side_effect=OSError('synthetic broker failure')): + scheduler.tick() + stored = RedBeatSchedulerEntry.from_key(entry.key, app=app) + assert stored.total_run_count == 1 + assert stored.last_run_at == due + assert ( + app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + == (due + timedelta(seconds=60)).timestamp() + ) + + +def test_competing_creators_store_one_consistent_winner(app): + app.now = lambda: NOW + start = Barrier(8) + + def create(number): + entry = RedBeatSchedulerEntry( + name='competing-creators', + task='validation.noop', + schedule=schedule(60, app=app), + kwargs={'creator': number}, + app=app, + ) + due = NOW + timedelta(seconds=number + 1) + start.wait(timeout=10) + try: + entry.save_with_first_due(due, f'creator-{number}') + except (ValueError, WatchError): + return None + return number + + with ThreadPoolExecutor(max_workers=8) as executor: + winners = [n for n in executor.map(create, range(8)) if n is not None] + assert len(winners) == 1 + winner = winners[0] + key = 'redbeat:competing-creators' + saved = RedBeatSchedulerEntry.from_key(key, app=app) + assert saved.kwargs == {'creator': winner} + assert saved.jitter_fingerprint == f'creator-{winner}' + due = NOW + timedelta(seconds=winner + 1) + assert saved.last_run_at == due - timedelta(seconds=60) + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, key) == due.timestamp() + assert not app.redbeat_redis.sismember('run_immediately', key) + + +def test_first_due_removes_stale_immediate_membership(app): + key = 'redbeat:first-due-test' + app.redbeat_redis.sadd('run_immediately', key, 'unrelated-entry') + entry = create_entry(app) + assert entry.key == key + assert not app.redbeat_redis.sismember('run_immediately', key) + assert app.redbeat_redis.sismember('run_immediately', 'unrelated-entry') diff --git a/tests/test_jitter_concurrent_updates.py b/tests/test_jitter_concurrent_updates.py new file mode 100644 index 00000000..c8daa2bb --- /dev/null +++ b/tests/test_jitter_concurrent_updates.py @@ -0,0 +1,394 @@ +import json +from datetime import datetime, timedelta, timezone +from unittest.mock import patch + +import pytest +from celery import Celery +from celery.schedules import schedule +from fakeredis import FakeRedis +from redis.exceptions import WatchError + +from redbeat.decoder import RedBeatJSONEncoder +from redbeat.schedulers import RedBeatScheduler, RedBeatSchedulerEntry +from tests.test_jitter_integration import app as redis_app # noqa: F401 - registers Redis fixture + +NOW = datetime(2026, 1, 1, 12, tzinfo=timezone.utc) +FINGERPRINT = 'test-policy-v1' + + +@pytest.fixture(params=['memory', 'redis']) +def app(request): + if request.param == 'redis': + result = request.getfixturevalue('redis_app') + result.now = lambda: NOW + yield result + return + result = Celery('jitter-concurrent-tests', broker='memory://', set_as_current=False) + result.conf.update(redbeat_redis_url='redis://unused/0', timezone='UTC') + result.redbeat_redis = FakeRedis(decode_responses=True) + result.now = lambda: NOW + yield result + result.close() + + +def create_entry(app, due=NOW, **kwargs): + initial = RedBeatSchedulerEntry( + 'concurrent-entry', 'tasks.test', schedule(60, app=app), app=app, **kwargs + ) + return initial.save_with_first_due(due, FINGERPRINT) + + +def load(entry): + return RedBeatSchedulerEntry.from_key(entry.key, app=entry.app) + + +def test_reservation_preserves_latest_payload_and_entry_fields(app): + stale = create_entry(app, kwargs={'value': 'old'}, options={'expires': 60}) + current = load(stale) + current.kwargs = {'value': 'new'} + current.args = ['new-argument'] + current.options = {'expires': 120, 'queue': 'new-queue'} + current.enabled = False + current.update_definition() + current_definition = app.redbeat_redis.hget(stale.key, 'definition') + + reserved = next(stale) + stored = load(stale) + + assert stored.kwargs == {'value': 'new'} + assert stored.args == ['new-argument'] + assert stored.options == current.options + assert not stored._strtobool(stored.enabled) + # The outgoing invocation uses its loaded payload, while future runs keep + # the newer definition stored by the concurrent update. + assert reserved.kwargs == {'value': 'old'} + assert reserved.args is None + assert reserved.options == {'expires': 60} + assert reserved._strtobool(reserved.enabled) + assert stored.last_run_at == NOW + assert stored.total_run_count == 1 + assert app.redbeat_redis.hget(stale.key, 'definition') == current_definition + assert ( + app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, stale.key) + == (NOW + timedelta(seconds=60)).timestamp() + ) + + +def test_reservation_does_not_resurrect_deleted_managed_entry(app): + stale = create_entry(app) + stale.delete() + + with pytest.raises(KeyError): + next(stale) + + assert not app.redbeat_redis.exists(stale.key) + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, stale.key) is None + + +def test_reservation_does_not_overwrite_recreated_entry_with_same_policy(app): + stale = create_entry(app) + stale.delete() + replacement = create_entry(app, NOW + timedelta(seconds=30), kwargs={'value': 'replacement'}) + before = app.redbeat_redis.hgetall(replacement.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, replacement.key) + + with pytest.raises(KeyError): + next(stale) + + assert app.redbeat_redis.hgetall(replacement.key) == before + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, replacement.key) == score + + +def test_reservation_preserves_new_immediate_request_after_entry_was_loaded(app): + stale = create_entry(app) + current = load(stale) + current.request_run(NOW, run_immediately=True) + requested_score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, stale.key) + + with pytest.raises(ValueError): + next(stale) + stored = load(stale) + + assert stored._strtobool(stored.run_immediately) + assert app.redbeat_redis.sismember('run_immediately', stale.key) + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, stale.key) == requested_score + + # Reserving the reloaded request clears it and starts normal recurrence. + app.now = lambda: NOW + timedelta(seconds=1) + assert stored.is_due()[0] + next(stored) + finished = load(stale) + assert not finished._strtobool(finished.run_immediately) + assert not app.redbeat_redis.sismember('run_immediately', stale.key) + assert finished.total_run_count == 1 + assert ( + app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, stale.key) + == (NOW + timedelta(seconds=61)).timestamp() + ) + + +def test_stale_reservation_cannot_replace_a_completed_reservation(app): + initial = create_entry(app) + stale = load(initial) + next(initial) + before = app.redbeat_redis.hgetall(initial.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) + with pytest.raises(ValueError, match='run state'): + next(stale) + assert app.redbeat_redis.hgetall(initial.key) == before + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) == score + + +@pytest.mark.parametrize( + 'change,error,message', + [ + ('deleted', KeyError, None), + ('recreated', KeyError, None), + ('policy', ValueError, 'The applied jitter policy changed'), + ('interval', ValueError, 'interval changed before reservation'), + ('run-state', ValueError, 'The schedule run state changed before reservation'), + ], +) +def test_invalid_reservation_state_is_not_written_or_retried(app, change, error, message): + stale = create_entry(app) + if change == 'deleted': + stale.delete() + elif change == 'recreated': + stale.delete() + create_entry(app, NOW + timedelta(seconds=30)) + elif change == 'policy': + app.redbeat_redis.hset(stale.key, 'jitter_fingerprint', json.dumps('changed-policy')) + elif change == 'interval': + current = load(stale) + current.schedule = schedule(120, app=app) + current.save() + else: + next(load(stale)) + + before = app.redbeat_redis.hgetall(stale.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, stale.key) + immediate = app.redbeat_redis.sismember('run_immediately', stale.key) + pipeline_class = type(app.redbeat_redis.pipeline()) + original_watch = pipeline_class.watch + watch_calls = [] + + def record_watch(pipe, *keys): + watch_calls.append(keys) + return original_watch(pipe, *keys) + + with ( + patch.object(pipeline_class, 'watch', record_watch), + patch.object(pipeline_class, 'execute') as execute, + ): + with pytest.raises(error, match=message): + next(stale) + execute.assert_not_called() + + assert watch_calls == [(stale.key,)] + assert app.redbeat_redis.hgetall(stale.key) == before + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, stale.key) == score + assert app.redbeat_redis.sismember('run_immediately', stale.key) == immediate + + +def test_definition_update_does_not_restore_consumed_initial_note(app): + stale = create_entry( + app, kwargs={'value': 'old'}, first_run_kwargs={'bootstrap_token': 'first'} + ) + next(load(stale)) + stale.kwargs['value'] = 'new' + stale.update_definition() + + stored = load(stale) + assert stored.kwargs == {'value': 'new'} + assert stored.first_run_kwargs == {} + assert stored.total_run_count == 1 + assert stored.last_run_at == NOW + + +def test_definition_update_retries_metadata_watch_conflict(app): + current = create_entry(app, kwargs={'value': 'old'}) + current.kwargs = {'value': 'new'} + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + writes = [] + + def conflict_once(pipe, *args, **kwargs): + if not writes: + writes.append(True) + app.redbeat_redis.hset( + current.key, + 'meta', + json.dumps({'last_run_at': NOW, 'total_run_count': 8}, cls=RedBeatJSONEncoder), + ) + return execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', conflict_once): + current.update_definition() + + stored = load(current) + assert writes == [True] + assert stored.kwargs == {'value': 'new'} + assert stored.total_run_count == 8 + assert stored.last_run_at == NOW + + +def test_definition_update_preserves_latest_first_run_kwargs(app): + stale = create_entry(app, first_run_kwargs={'bootstrap_token': 'old'}) + current = load(stale) + current.first_run_kwargs = {'bootstrap_token': 'new', 'other': 2} + current.save() + stale.kwargs = {'payload': 'updated'} + + stale.update_definition() + stored = load(stale) + + assert stored.kwargs == {'payload': 'updated'} + assert stored.first_run_kwargs == {'bootstrap_token': 'new', 'other': 2} + + +def test_reservation_does_not_consume_newer_first_run_kwargs(app): + stale = create_entry(app, first_run_kwargs={'bootstrap_token': 'old'}) + current = load(stale) + current.first_run_kwargs = {'bootstrap_token': 'new'} + current.save() + before = app.redbeat_redis.hget(stale.key, 'definition') + + outgoing = next(stale) + stored = load(stale) + + assert outgoing.kwargs == {'bootstrap_token': 'old'} + assert stored.first_run_kwargs == {'bootstrap_token': 'new'} + assert app.redbeat_redis.hget(stale.key, 'definition') == before + assert next(stored).kwargs == {'bootstrap_token': 'new'} + assert load(stale).first_run_kwargs == {} + + +def test_reservation_retries_payload_watch_conflict(app): + stale = create_entry(app, kwargs={'value': 'old'}) + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + writes = [] + + def conflict_once(pipe, *args, **kwargs): + if not writes: + writes.append(True) + definition = stale._jitter_definition() + definition['kwargs'] = {'value': 'new'} + definition['options'] = {'expires': 120, 'queue': 'new-queue'} + app.redbeat_redis.hset( + stale.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder) + ) + return execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', conflict_once): + reserved = next(stale) + + stored = load(stale) + assert writes == [True] + assert stored.kwargs == {'value': 'new'} + assert stored.options == {'expires': 120, 'queue': 'new-queue'} + assert reserved.kwargs == {'value': 'old'} + assert reserved.options == {} + assert stored.total_run_count == 1 + assert stored.last_run_at == NOW + + +@pytest.mark.parametrize('operation', ['definition', 'reservation']) +def test_managed_write_stops_after_three_watch_conflicts(app, operation): + initial = create_entry(app, kwargs={'value': 'old'}) + before = app.redbeat_redis.hgetall(initial.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) + initial.kwargs = {'value': 'new'} + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + attempts = [] + + def conflict_every_time(pipe, *args, **kwargs): + attempts.append(True) + app.redbeat_redis.hset(initial.key, 'concurrent_value', str(len(attempts))) + return execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', conflict_every_time): + with pytest.raises(WatchError): + if operation == 'definition': + initial.update_definition() + else: + next(initial) + + assert len(attempts) == 3 + after = app.redbeat_redis.hgetall(initial.key) + assert {key: value for key, value in after.items() if key != 'concurrent_value'} == before + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) == score + + +def test_exhausted_managed_immediate_request_keeps_its_due_for_next_selection(app): + initial = RedBeatSchedulerEntry( + 'concurrent-immediate', 'tasks.test', schedule(1800, app=app), app=app + ).save_with_first_due(NOW + timedelta(seconds=1800), FINGERPRINT) + initial.request_run(NOW, run_immediately=True) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + attempts = [] + + def conflict_reservation(pipe, *args, **kwargs): + reserving = any( + command[0][:3] == ('HSET', initial.key, 'meta') for command in pipe.command_stack + ) + if reserving: + attempts.append(True) + app.redbeat_redis.hset(initial.key, 'concurrent_value', str(len(attempts))) + return execute(pipe, *args, **kwargs) + + scheduler = RedBeatScheduler(app, lazy=True, max_interval=1) + try: + with patch.object(app, 'send_task') as publish: + with patch.object(pipeline_class, 'execute', conflict_reservation): + scheduler.tick() + + assert len(attempts) == 3 + publish.assert_not_called() + assert not app.redbeat_redis.sismember('run_immediately', initial.key) + assert load(initial)._strtobool(load(initial).run_immediately) + assert load(initial).total_run_count == 0 + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) == score + # The due score remains after selection drains the immediate set, + # so the next tick can retry this request through the schedule index. + scheduler.tick() + publish.assert_called_once() + stored = load(initial) + assert stored.total_run_count == 1 + assert not stored._strtobool(stored.run_immediately) + finally: + scheduler.close() + + +def test_tick_does_not_create_immediate_request_for_failed_normal_reservation(app): + initial = create_entry(app) + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + attempts = [] + + def conflict_reservation(pipe, *args, **kwargs): + reserving = any( + command[0][:3] == ('HSET', initial.key, 'meta') for command in pipe.command_stack + ) + if reserving: + attempts.append(True) + app.redbeat_redis.hset(initial.key, 'concurrent_value', str(len(attempts))) + return execute(pipe, *args, **kwargs) + + scheduler = RedBeatScheduler(app, lazy=True, max_interval=1) + try: + with patch.object(app, 'send_task') as publish: + with patch.object(pipeline_class, 'execute', conflict_reservation): + scheduler.tick() + assert len(attempts) == 3 + publish.assert_not_called() + assert not app.redbeat_redis.sismember('run_immediately', initial.key) + assert not load(initial)._strtobool(load(initial).run_immediately) + assert load(initial).total_run_count == 0 + scheduler.tick() + publish.assert_called_once() + finally: + scheduler.close() diff --git a/tests/test_jitter_integration.py b/tests/test_jitter_integration.py new file mode 100644 index 00000000..dc28dcbe --- /dev/null +++ b/tests/test_jitter_integration.py @@ -0,0 +1,188 @@ +import os +import shutil +import subprocess +import time +from datetime import datetime, timedelta, timezone +from queue import Empty +from uuid import uuid4 + +import pytest +from celery import Celery +from celery.schedules import schedule +from redis import Redis +from redis.exceptions import ConnectionError + +from redbeat.decoder import to_timestamp +from redbeat.schedulers import RedBeatScheduler, RedBeatSchedulerEntry + +NOW = datetime(2026, 1, 1, 12, tzinfo=timezone.utc) +FINGERPRINT = 'test-policy-v1' + + +@pytest.fixture +def app(tmp_path): + executable = os.environ.get('REDBEAT_TEST_REDIS_SERVER') + if not executable: + pytest.skip('Set REDBEAT_TEST_REDIS_SERVER to an isolated Redis test binary') + executable = shutil.which(executable) + if not executable: + pytest.fail('The requested Redis test binary is unavailable') + socket_path = str(tmp_path / 'redis.sock') + process = subprocess.Popen( + [ + executable, + '--port', + '0', + '--unixsocket', + socket_path, + '--unixsocketperm', + '700', + '--save', + '', + '--appendonly', + 'no', + '--dir', + str(tmp_path), + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.STDOUT, + ) + client = Redis(unix_socket_path=socket_path, decode_responses=True) + result = None + try: + deadline = time.monotonic() + 5 + while True: + if process.poll() is not None: + pytest.fail('Isolated Redis exited before startup') + try: + client.ping() + break + except ConnectionError: + if time.monotonic() >= deadline: + pytest.fail('Isolated Redis did not become ready') + time.sleep(0.02) + result = Celery('real-jitter-tests', broker='memory://', set_as_current=False) + result.conf.update( + redbeat_redis_url='redis://unused/0', + timezone='UTC', + task_default_queue='jitter-' + uuid4().hex, + ) + result.redbeat_redis = client + yield result + finally: + if result is not None: + result.close() + client.close() + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + +def read_message(queue): + try: + return queue.get(block=False) + except Empty: + return None + + +@pytest.mark.parametrize( + 'interval,first_delay', + [(60, 102), (300, 356), (600, 22), (1800, 35), (1.5, 2.25), (0.5, 0.000001)], +) +def test_real_redis_reload_lookahead_and_beat_publication(app, interval, first_delay): + app.now = lambda: NOW + due = NOW + timedelta(seconds=first_delay) + initial = RedBeatSchedulerEntry( + name='test-first-run', + task='tasks.test', + schedule=schedule(interval, app=app), + kwargs={'job_id': 'job-01'}, + options={'expires': 120}, + app=app, + ) + initial.save_with_first_due(due, FINGERPRINT, first_run_kwargs={'bootstrap_token': 'first'}) + loaded = RedBeatSchedulerEntry.from_key(initial.key, app) + assert loaded.last_run_at == due - timedelta(seconds=interval) + assert loaded.jitter_fingerprint == FINGERPRINT + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) == to_timestamp(due) + # Updating the payload must preserve the stored first due. + loaded.kwargs['revision'] = 'updated' + loaded.update_definition() + scheduler = RedBeatScheduler(app, lazy=True, max_interval=3600) + with app.connection_for_read() as connection: + queue = connection.SimpleQueue(app.conf.task_default_queue) + try: + for now in (NOW, due - timedelta(microseconds=1)): + app.now = lambda: now + # Selection can include the entry before is_due() permits dispatch. + assert 'test-first-run' in scheduler.schedule + scheduler.tick() + assert read_message(queue) is None + app.now = lambda: due + # A replacement scheduler models Beat reload with Redis retained. + scheduler = RedBeatScheduler(app, lazy=True, max_interval=3600) + scheduler.tick() + message = read_message(queue) + assert message is not None + assert message.payload[1]['bootstrap_token'] == 'first' + assert message.payload[1]['revision'] == 'updated' + assert message.headers.get('expires') is not None + message.ack() + assert read_message(queue) is None + stored = RedBeatSchedulerEntry.from_key(initial.key, app) + assert 'bootstrap_token' not in stored.kwargs + assert stored.first_run_kwargs == {} + assert stored.total_run_count == 1 + assert stored.last_run_at == due + next_due = due + timedelta(seconds=interval) + assert app.redbeat_redis.zscore( + app.redbeat_conf.schedule_key, initial.key + ) == to_timestamp(next_due) + app.now = lambda: next_due - timedelta(microseconds=1) + scheduler.tick() + assert read_message(queue) is None + app.now = lambda: next_due + scheduler.tick() + message = read_message(queue) + assert message is not None + assert 'bootstrap_token' not in message.payload[1] + message.ack() + assert list(app.redbeat_redis.scan_iter('redbeat:test-first-run')) == [initial.key] + finally: + queue.close() + scheduler.close() + + +@pytest.mark.parametrize('interval', [2, 0.5]) +def test_real_clock_dispatch_is_not_early_and_recurs(app, interval): + due = datetime.now(timezone.utc) + timedelta(seconds=2) + initial = RedBeatSchedulerEntry( + 'real-clock-test', + 'tasks.test', + schedule(interval, app=app), + app=app, + ).save_with_first_due(due, FINGERPRINT) + scheduler = RedBeatScheduler(app, lazy=True, max_interval=0.05) + observed = [] + with app.connection_for_read() as connection: + queue = connection.SimpleQueue(app.conf.task_default_queue) + try: + deadline = time.monotonic() + 8 + while len(observed) < 2 and time.monotonic() < deadline: + scheduler.tick() + message = read_message(queue) + if message is not None: + observed.append(datetime.now(timezone.utc)) + message.ack() + time.sleep(0.02) + assert len(observed) == 2 + assert timedelta(0) <= observed[0] - due < timedelta(seconds=1) + # After the first reservation, runs follow the normal interval. + assert interval - 0.2 <= (observed[1] - observed[0]).total_seconds() < interval + 1 + assert RedBeatSchedulerEntry.from_key(initial.key, app).total_run_count == 2 + finally: + queue.close() + scheduler.close() diff --git a/tests/test_jitter_worker_integration.py b/tests/test_jitter_worker_integration.py new file mode 100644 index 00000000..46e7eea4 --- /dev/null +++ b/tests/test_jitter_worker_integration.py @@ -0,0 +1,85 @@ +import time +from datetime import datetime, timedelta, timezone +from threading import Event +from uuid import uuid4 + +import pytest +from celery.contrib.testing.worker import start_worker +from celery.schedules import schedule + +from redbeat.schedulers import RedBeatScheduler, RedBeatSchedulerEntry +from tests.test_jitter_integration import FINGERPRINT +from tests.test_jitter_integration import app as redis_app + +app = redis_app + + +@pytest.fixture +def broker_app(app): + path = app.redbeat_redis.connection_pool.connection_kwargs['path'] + app.conf.update( + broker_url='redis+socket://' + path + '?virtual_host=1', + result_backend=None, + task_ignore_result=True, + worker_hijack_root_logger=False, + worker_enable_remote_control=False, + worker_prefetch_multiplier=1, + ) + return app + + +def worker(app): + return start_worker( + app, + pool='solo', + concurrency=1, + perform_ping_check=False, + without_heartbeat=True, + loglevel='ERROR', + shutdown_timeout=10, + ) + + +def save_entry(app, task, interval=600, options=None): + due = datetime.now(timezone.utc).replace(microsecond=0) + timedelta(seconds=2) + entry = RedBeatSchedulerEntry( + 'worker-' + uuid4().hex, + task, + schedule(interval, app=app), + options=options or {}, + app=app, + ).save_with_first_due(due, FINGERPRINT, first_run_kwargs={'bootstrap_token': 'first'}) + return entry, due + + +def test_real_broker_worker_first_context_and_recurrence(broker_app): + app = broker_app + calls = [] + completed = Event() + + @app.task(name='validation.' + uuid4().hex, shared=False, lazy=False) + def record(**kwargs): + calls.append((datetime.now(timezone.utc), dict(kwargs))) + if len(calls) >= 2: + completed.set() + + entry, due = save_entry(app, record.name, interval=2) + scheduler = RedBeatScheduler(app, lazy=True, max_interval=0.05) + try: + with worker(app): + deadline = time.monotonic() + 10 + while not completed.is_set() and time.monotonic() < deadline: + scheduler.tick() + time.sleep(0.02) + assert completed.is_set() + assert len(calls) == 2 + assert calls[0][0] >= due + assert (calls[1][0] - calls[0][0]).total_seconds() >= 1.8 + assert calls[0][1]['bootstrap_token'] == 'first' + assert 'bootstrap_token' not in calls[1][1] + stored = RedBeatSchedulerEntry.from_key(entry.key, app=app) + assert stored.total_run_count == 2 + assert 'bootstrap_token' not in stored.kwargs + assert stored.first_run_kwargs == {} + finally: + scheduler.close() diff --git a/tests/test_managed_lifecycle_limits.py b/tests/test_managed_lifecycle_limits.py new file mode 100644 index 00000000..a39a4895 --- /dev/null +++ b/tests/test_managed_lifecycle_limits.py @@ -0,0 +1,582 @@ +import json +from datetime import timedelta +from unittest.mock import patch +from uuid import UUID + +import pytest +from celery.beat import ScheduleEntry +from celery.schedules import schedule +from redis.exceptions import ConnectionError, WatchError + +from redbeat.schedulers import EntryAlreadyExists, RedBeatSchedulerEntry +from tests.test_jitter_concurrent_updates import app as lifecycle_app +from tests.test_jitter_concurrent_updates import create_entry, load +from tests.test_jitter_integration import FINGERPRINT, NOW +from tests.test_jitter_integration import app as redis_app # noqa: F401 + +app = lifecycle_app + + +def saved_state(entry): + client = entry.app.redbeat_redis + return ( + client.hgetall(entry.key), + client.zscore(entry.app.redbeat_conf.schedule_key, entry.key), + client.sismember('run_immediately', entry.key), + ) + + +def apply_operation(entry, operation): + if operation == 'definition': + entry.kwargs = {'payload': 'stale-update'} + return entry.update_definition() + if operation == 'request': + entry.kwargs = {'payload': 'stale-request'} + return entry.request_run(NOW + timedelta(seconds=20)) + return next(entry) + + +@pytest.mark.parametrize('operation', ['definition', 'request', 'reservation']) +def test_same_key_replacement_rejects_stale_operation_with_identical_timing(app, operation): + stale = create_entry(app, kwargs={'payload': 'old'}) + stale.delete() + replacement = create_entry(app, kwargs={'payload': 'replacement'}) + assert replacement.last_run_at == stale.last_run_at + assert replacement.total_run_count == stale.total_run_count + assert replacement.entry_id != stale.entry_id + before = saved_state(replacement) + + with pytest.raises(KeyError): + apply_operation(stale, operation) + + assert saved_state(replacement) == before + + +@pytest.mark.parametrize('operation', ['definition', 'request', 'reservation']) +@pytest.mark.parametrize('changed_state', ['policy', 'interval']) +def test_replacement_with_different_policy_or_interval_still_rejects_stale_operation( + app, operation, changed_state +): + stale = create_entry(app) + stale.delete() + replacement = create_entry(app) + if changed_state == 'policy': + app.redbeat_redis.hset(replacement.key, 'jitter_fingerprint', json.dumps('other-policy')) + else: + replacement.schedule = schedule(120, app=app) + replacement.request_run(NOW, run_immediately=True, fingerprint=FINGERPRINT) + before = saved_state(replacement) + + with pytest.raises(KeyError): + apply_operation(stale, operation) + + assert saved_state(replacement) == before + + +def test_replacement_with_different_run_metadata_still_rejects_stale_reservation(app): + stale = create_entry(app) + stale.delete() + replacement = create_entry(app, NOW + timedelta(seconds=30)) + before = saved_state(replacement) + + with pytest.raises(KeyError): + next(stale) + + assert saved_state(replacement) == before + + +@pytest.mark.parametrize('run_immediately', [False, True]) +def test_stale_same_key_reservation_preserves_replacements_newer_request(app, run_immediately): + stale = create_entry(app) + stale.delete() + replacement = create_entry(app, kwargs={'payload': 'replacement'}) + due = NOW if run_immediately else NOW + timedelta(seconds=20) + replacement.request_run(due, run_immediately=run_immediately) + before = saved_state(replacement) + + with pytest.raises(KeyError): + next(stale) + + stored = load(replacement) + assert stored.kwargs == replacement.kwargs + assert saved_state(replacement) == before + assert stored.total_run_count == 0 + assert stored.last_run_at == due - timedelta(seconds=60) + + +def test_second_loaded_reservation_rejects_changed_run_state(app): + first = create_entry(app) + second = load(first) + next(first) + before = saved_state(first) + + with pytest.raises(ValueError, match='run state'): + next(second) + + assert saved_state(first) == before + assert load(first).total_run_count == 1 + + +@pytest.mark.parametrize('remove_policy', [False, True]) +def test_following_timing_is_written_with_the_reservation(app, remove_policy): + entry = load( + create_entry( + app, + kwargs={'payload': 'current'}, + options={'queue': 'custom-queue', 'expires': 120}, + total_run_count=9, + ) + ) + before = saved_state(entry) + due = NOW + timedelta(seconds=120) + fingerprint = None if remove_policy else 'new-policy' + app.conf.redbeat_entry_policy = lambda following: (due, fingerprint) + pipeline_class = type(app.redbeat_redis.pipeline()) + original_execute = pipeline_class.execute + writes = [] + + def execute(pipe, *args, **kwargs): + commands = [command for command, _ in pipe.command_stack] + if any(command[0] == 'ZADD' for command in commands): + assert saved_state(entry) == before + writes.append(commands) + return original_execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', execute): + outgoing = next(entry) + + assert len(writes) == 1 + assert [command[0] for command in writes[0]] == [ + 'HSET', + 'HDEL' if remove_policy else 'HSET', + 'ZADD', + 'SREM', + ] + + stored = load(entry) + assert stored.kwargs == entry.kwargs + assert stored.options == entry.options + assert stored.total_run_count == 10 + assert outgoing.last_run_at == NOW + assert outgoing.total_run_count == 10 + assert stored.last_run_at == due - timedelta(seconds=60) + assert stored.first_run_kwargs == {} + assert not stored._strtobool(stored.run_immediately) + assert not app.redbeat_redis.sismember('run_immediately', entry.key) + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) == due.timestamp() + assert stored.jitter_fingerprint == fingerprint + if remove_policy: + assert not app.redbeat_redis.hexists(entry.key, 'jitter_fingerprint') + + +@pytest.mark.parametrize('due', [None, NOW + timedelta(seconds=120)]) +@pytest.mark.parametrize('fingerprint', ['', False, 42]) +def test_invalid_following_policy_keeps_normal_reservation(app, due, fingerprint): + entry = load(create_entry(app)) + app.conf.redbeat_entry_policy = lambda following: (due, fingerprint) + next(entry) + stored = load(entry) + assert stored.last_run_at == NOW + assert stored.total_run_count == 1 + assert stored.jitter_fingerprint == FINGERPRINT + assert ( + app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + == (NOW + timedelta(seconds=60)).timestamp() + ) + + +def test_following_timing_keeps_exact_state_after_repeated_watch_conflicts(app): + entry = load(create_entry(app)) + before = saved_state(entry) + app.conf.redbeat_entry_policy = lambda following: (NOW + timedelta(seconds=120), 'new-policy') + pipeline_class = type(app.redbeat_redis.pipeline()) + original_execute = pipeline_class.execute + attempts = [] + + def execute(pipe, *args, **kwargs): + if any(command[0] == 'ZADD' for command, _ in pipe.command_stack): + attempts.append(True) + app.redbeat_redis.hset(entry.key, 'concurrent_value', str(len(attempts))) + return original_execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', execute): + with pytest.raises(WatchError): + next(entry) + + assert len(attempts) == 3 + after = saved_state(entry) + assert after[0].pop('concurrent_value') == '3' + assert after == before + + +def test_watch_conflict_rejects_identical_timing_replacement_after_reload(app): + stale = create_entry(app, kwargs={'payload': 'old'}) + pipeline_class = type(app.redbeat_redis.pipeline()) + original_execute = pipeline_class.execute + replaced = [] + replacement_state = [] + + def replace_before_commit(pipe, *args, **kwargs): + if not replaced: + replaced.append(True) + with patch.object(pipeline_class, 'execute', original_execute): + stale.delete() + replacement = create_entry(app, kwargs={'payload': 'replacement'}) + replacement_state.append(saved_state(replacement)) + return original_execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', replace_before_commit): + with pytest.raises(KeyError): + next(stale) + + assert replaced == [True] + assert saved_state(stale) == replacement_state[0] + assert load(stale).total_run_count == 0 + assert load(stale).kwargs == {'payload': 'replacement'} + + +def test_ordinary_entry_does_not_acquire_managed_state(app): + entry = RedBeatSchedulerEntry( + 'ordinary-entry', 'tasks.test', schedule(60, app=app), app=app + ).save() + next(load(entry)) + stored = load(entry) + stored.kwargs = {'payload': 'ordinary'} + stored.save() + + assert not stored.jitter_fingerprint + fields = app.redbeat_redis.hgetall(entry.key) + assert 'jitter_fingerprint' not in fields + assert 'entry_id' not in fields + assert stored.entry_id is None + assert 'entry_id' not in json.loads(fields['definition']) + + +def test_guarded_creation_assigns_identity_and_preserves_it_during_updates(app): + entry = RedBeatSchedulerEntry( + 'ordinary-entry', 'tasks.test', schedule(60, app=app), app=app + ).save_guarded(create=True) + assert UUID(entry.entry_id).version == 4 + assert load(entry).entry_id == entry.entry_id + assert json.loads(app.redbeat_redis.hget(entry.key, 'entry_id')) == entry.entry_id + assert 'entry_id' not in json.loads(app.redbeat_redis.hget(entry.key, 'definition')) + entry.kwargs = {'payload': 'updated'} + updated = entry.save_guarded() + assert updated.entry_id == entry.entry_id + assert updated.kwargs == entry.kwargs + assert updated.jitter_fingerprint is None + + +def test_identified_ordinary_reservation_keeps_definition_and_normal_interval(app): + entry = RedBeatSchedulerEntry( + 'ordinary-entry', + 'tasks.test', + schedule(60, app=app), + app=app, + kwargs={'payload': 'current'}, + ).save_guarded(create=True) + before = app.redbeat_redis.hget(entry.key, 'definition') + outgoing = next(load(entry)) + stored = load(entry) + assert stored.entry_id == outgoing.entry_id == entry.entry_id + assert stored.kwargs == outgoing.kwargs == entry.kwargs + assert stored.total_run_count == 1 + assert stored.last_run_at == NOW + assert stored.jitter_fingerprint is None + assert app.redbeat_redis.hget(entry.key, 'definition') == before + assert ( + app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + == (NOW + timedelta(seconds=60)).timestamp() + ) + + +@pytest.mark.parametrize('operation', ['save', 'reservation']) +def test_guarded_ordinary_replacement_rejects_stale_writes(app, operation): + stale = RedBeatSchedulerEntry( + 'ordinary-entry', 'tasks.test', schedule(60, app=app), app=app + ).save_guarded(create=True) + stale.delete() + replacement = RedBeatSchedulerEntry( + stale.name, + 'tasks.test', + schedule(60, app=app), + app=app, + kwargs={'payload': 'replacement'}, + ).save_guarded(create=True) + before = saved_state(replacement) + with pytest.raises(KeyError): + if operation == 'save': + stale.save_guarded() + else: + next(stale) + assert saved_state(replacement) == before + + +@pytest.mark.parametrize('identified', [False, True]) +@pytest.mark.parametrize('phased', [False, True]) +def test_guarded_creation_refuses_existing_definition_or_orphan_hash(app, identified, phased): + entry = RedBeatSchedulerEntry('ordinary-entry', 'tasks.test', schedule(60, app=app), app=app) + if identified: + entry.save_guarded(create=True) + else: + app.redbeat_redis.hset(entry.key, 'meta', '{}') + before = saved_state(entry) + identity = entry.entry_id + with pytest.raises(EntryAlreadyExists, match='existing schedule hash'): + if phased: + entry.save_with_first_due(NOW, FINGERPRINT) + else: + entry.save_guarded(create=True) + assert saved_state(entry) == before + assert entry.entry_id == identity + + +@pytest.mark.parametrize('phased', [False, True]) +@pytest.mark.parametrize( + 'failure,conflicts', [(WatchError, 1), (WatchError, 3), (ConnectionError, 1)] +) +def test_creation_assigns_identity_only_after_successful_commit(app, phased, failure, conflicts): + entry = RedBeatSchedulerEntry('ordinary-entry', 'tasks.test', schedule(60, app=app), app=app) + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + attempts = [] + + def commit(pipe, *args, **kwargs): + if any(command[0][0] == 'ZADD' for command in pipe.command_stack): + assert entry.entry_id is None + attempts.append(True) + if len(attempts) <= conflicts: + raise failure('creation did not commit') + return execute(pipe, *args, **kwargs) + + def create(): + if phased: + return entry.save_with_first_due(NOW, FINGERPRINT) + return entry.save_guarded(create=True) + + with patch.object(pipeline_class, 'execute', commit): + if failure is WatchError and conflicts == 1: + stored = create() + assert entry.entry_id == stored.entry_id == load(entry).entry_id + assert UUID(entry.entry_id).version == 4 + else: + with pytest.raises(failure): + create() + assert entry.entry_id is None + assert saved_state(entry) == ({}, None, False) + assert len(attempts) == (min(conflicts + 1, 3) if failure is WatchError else 1) + + +@pytest.mark.parametrize('phased', [False, True]) +def test_creation_conflict_preserves_the_winner_and_losing_callers_identity(app, phased): + entry = RedBeatSchedulerEntry('ordinary-entry', 'tasks.test', schedule(60, app=app), app=app) + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + winner = [] + winner_state = [] + + def commit(pipe, *args, **kwargs): + if not winner and any(command[0][0] == 'ZADD' for command in pipe.command_stack): + replacement = RedBeatSchedulerEntry( + entry.name, entry.task, entry.schedule, app=app, kwargs={'payload': 'winner'} + ) + winner.append(replacement) + replacement.save_guarded(create=True) + winner_state.append(saved_state(replacement)) + return execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', commit): + with pytest.raises(EntryAlreadyExists): + if phased: + entry.save_with_first_due(NOW, FINGERPRINT) + else: + entry.save_guarded(create=True) + assert entry.entry_id is None + assert saved_state(entry) == winner_state[0] + assert load(entry).entry_id == winner[0].entry_id + + +@pytest.mark.parametrize('operation', ['save', 'reservation']) +def test_legacy_none_identity_rejects_new_identified_replacement(app, operation): + stale = RedBeatSchedulerEntry( + 'ordinary-entry', 'tasks.test', schedule(60, app=app), app=app + ).save() + assert stale.entry_id is None + stale.delete() + replacement = RedBeatSchedulerEntry( + stale.name, 'tasks.test', schedule(60, app=app), app=app + ).save_guarded(create=True) + before = saved_state(replacement) + with pytest.raises(KeyError): + if operation == 'save': + stale.save_guarded() + else: + app.conf.redbeat_entry_policy = lambda entry: (None, 'new-policy') + next(stale) + assert saved_state(replacement) == before + + +@pytest.mark.parametrize('operation', ['definition', 'request', 'reservation']) +def test_legacy_managed_copy_rejects_identified_replacement(app, operation): + original = create_entry(app) + app.redbeat_redis.hdel(original.key, 'entry_id') + stale = load(original) + assert stale.entry_id is None + stale.delete() + replacement = create_entry(app) + before = saved_state(replacement) + with pytest.raises(KeyError): + apply_operation(stale, operation) + assert saved_state(replacement) == before + + +@pytest.mark.parametrize('serializer', ['save', 'reschedule', 'update', 'reservation']) +def test_identity_survives_existing_definition_writers(app, serializer): + entry = create_entry(app) + identity = entry.entry_id + fingerprint = entry.jitter_fingerprint + if serializer == 'save': + entry.save() + elif serializer == 'reschedule': + entry.reschedule() + elif serializer == 'update': + entry.kwargs = {'payload': 'updated'} + entry.update_definition() + else: + assert next(entry).entry_id == identity + assert load(entry).entry_id == identity + assert load(entry).jitter_fingerprint == fingerprint + assert 'entry_id' not in load(entry).kwargs + assert 'entry_id' not in json.loads(app.redbeat_redis.hget(entry.key, 'definition')) + assert json.loads(app.redbeat_redis.hget(entry.key, 'entry_id')) == identity + + +def test_disabled_identified_entry_still_rejects_stale_reservation(app): + entry = create_entry(app) + identity = entry.entry_id + app.conf.redbeat_entry_policy = lambda following: (None, None) + next(entry) + stale = load(entry) + assert stale.entry_id == identity + assert stale.jitter_fingerprint is None + stale.delete() + replacement = RedBeatSchedulerEntry( + stale.name, 'tasks.test', schedule(60, app=app), app=app + ).save_guarded(create=True) + before = saved_state(replacement) + with pytest.raises(KeyError): + next(stale) + assert saved_state(replacement) == before + + +def test_policy_adoption_and_updates_do_not_assign_legacy_identity(app): + entry = RedBeatSchedulerEntry( + 'ordinary-entry', 'tasks.test', schedule(60, app=app), app=app + ).save() + entry.save_guarded() + app.conf.redbeat_entry_policy = lambda following: (None, FINGERPRINT) + next(load(entry)) + managed = load(entry) + managed.kwargs = {'payload': 'updated'} + managed.update_definition() + assert load(entry).entry_id is None + assert load(entry).jitter_fingerprint == FINGERPRINT + assert 'entry_id' not in json.loads(app.redbeat_redis.hget(entry.key, 'definition')) + assert not app.redbeat_redis.hexists(entry.key, 'entry_id') + + +@pytest.mark.parametrize('phased', [False, True]) +def test_creation_identity_adds_no_unknown_fields_for_legacy_constructor(app, phased): + if phased: + entry = create_entry(app) + else: + entry = RedBeatSchedulerEntry( + 'ordinary-entry', 'tasks.test', schedule(60, app=app), app=app + ).save_guarded(create=True) + definition = entry.decode_definition(app.redbeat_redis.hget(entry.key, 'definition')) + metadata = entry.decode_meta(app.redbeat_redis.hget(entry.key, 'meta')) + assert 'entry_id' not in definition + assert json.loads(app.redbeat_redis.hget(entry.key, 'entry_id')) == entry.entry_id + for field in ('enabled', 'run_immediately', 'target'): + definition.pop(field, None) + definition.update(metadata) + legacy = ScheduleEntry(app=app, **definition) + assert legacy.name == entry.name + assert legacy.task == entry.task + assert legacy.last_run_at == entry.last_run_at + assert legacy.kwargs == entry.kwargs + + +def test_entry_load_uses_existing_hget_pattern_and_preserves_creation_identity(app): + entry = create_entry(app, kwargs={'payload': 'current'}) + pipeline_class = type(app.redbeat_redis.pipeline()) + original_execute = pipeline_class.execute + commands = [] + + def execute(pipe, *args, **kwargs): + commands.extend(command for command, _ in pipe.command_stack) + return original_execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', execute): + loaded = load(entry) + + assert commands == [ + ('HGET', entry.key, 'definition'), + ('HGET', entry.key, 'meta'), + ('HGET', entry.key, 'jitter_fingerprint'), + ('HGET', entry.key, 'entry_id'), + ] + assert loaded.entry_id == entry.entry_id + assert loaded.kwargs == entry.kwargs + assert loaded.last_run_at == entry.last_run_at + assert loaded.jitter_fingerprint == entry.jitter_fingerprint + + +@pytest.mark.parametrize('value', [None, '', '"creation-id"', b'"creation-id"']) +def test_optional_json_decoder_accepts_missing_text_and_bytes(value): + assert RedBeatSchedulerEntry.decode_json(value) == ('creation-id' if value else None) + + +@pytest.mark.parametrize('writer', ['save', 'reschedule']) +@pytest.mark.parametrize('target', [None, 'generic-library-target']) +def test_identified_ordinary_immediate_reservation_keeps_legacy_serializers(app, writer, target): + entry = RedBeatSchedulerEntry( + 'ordinary-entry', + 'tasks.test', + schedule(60, app=app), + app=app, + kwargs={'payload': 'current'}, + target=target, + run_immediately=True, + ).save_guarded(create=True) + getattr(entry, writer)() + current = load(entry) + assert current.is_due()[0] + assert not current._strtobool(current.run_immediately) + outgoing = next(current) + stored = load(entry) + assert outgoing.kwargs == stored.kwargs == {'payload': 'current'} + assert stored.entry_id == entry.entry_id + assert stored.total_run_count == 1 + assert not stored._strtobool(stored.run_immediately) + assert not app.redbeat_redis.sismember('run_immediately', entry.key) + + +def test_disabled_identified_policy_can_consume_an_ordinary_immediate_request(app): + entry = create_entry(app) + app.conf.redbeat_entry_policy = lambda following: (None, None) + next(entry) + current = load(entry) + assert current.jitter_fingerprint is None + current.run_immediately = True + current.target = 'generic-library-target' + current.reschedule() + immediate = load(entry) + previous_count = immediate.total_run_count + assert immediate.is_due()[0] + next(immediate) + stored = load(entry) + assert stored.total_run_count == previous_count + 1 + assert stored.entry_id == entry.entry_id + assert stored.jitter_fingerprint is None + assert not stored._strtobool(stored.run_immediately) diff --git a/tests/test_managed_requests.py b/tests/test_managed_requests.py new file mode 100644 index 00000000..5ba501d2 --- /dev/null +++ b/tests/test_managed_requests.py @@ -0,0 +1,344 @@ +from datetime import timedelta +from unittest.mock import patch + +import pytest +from celery.schedules import schedule +from redis.exceptions import WatchError + +from redbeat.schedulers import RedBeatScheduler, RedBeatSchedulerEntry +from tests.test_jitter_concurrent_updates import app as request_app +from tests.test_jitter_concurrent_updates import create_entry, load +from tests.test_jitter_integration import NOW +from tests.test_jitter_integration import app as redis_app # noqa: F401 + +app = request_app + + +def test_delayed_request_uses_existing_anchor_and_guards_lookahead(app): + entry = create_entry(app, NOW, kwargs={'value': 'old'}) + next(entry) + entry = load(entry) + due = NOW + timedelta(seconds=80) + entry.kwargs = {'value': 'new'} + entry.request_run(due) + stored = load(entry) + assert stored.kwargs == {'value': 'new'} + assert stored.last_run_at == due - timedelta(seconds=60) + assert stored.total_run_count == 1 + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) == due.timestamp() + assert stored._strtobool(stored.run_immediately) + assert not app.redbeat_redis.sismember('run_immediately', entry.key) + scheduler = RedBeatScheduler(app, lazy=True, max_interval=3600) + try: + with patch.object(app, 'send_task') as publish: + for seconds in (0, 60, 79.999999): + app.now = lambda: NOW + timedelta(seconds=seconds) + scheduler.tick() + publish.assert_not_called() + app.now = lambda: due + scheduler.tick() + publish.assert_called_once() + finished = load(entry) + assert finished.last_run_at == due + assert finished.total_run_count == 2 + assert not finished._strtobool(finished.run_immediately) + assert ( + app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + == (due + timedelta(seconds=60)).timestamp() + ) + finally: + scheduler.close() + + +@pytest.mark.parametrize('order', [(False, True), (True, False)]) +def test_immediate_request_wins_in_either_arrival_order(app, order): + entry = create_entry(app, first_run_kwargs={'bootstrap': 'first'}) + for index, run_immediately in enumerate(order): + current = load(entry) + current.kwargs = {'revision': index} + due = NOW + timedelta(seconds=0 if run_immediately else 20) + current.request_run(due, run_immediately=run_immediately) + stored = load(entry) + assert stored.kwargs == {'revision': 1} + assert stored.last_run_at == NOW - timedelta(seconds=60) + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) == NOW.timestamp() + assert stored.first_run_kwargs == {} + assert stored._strtobool(stored.run_immediately) + assert app.redbeat_redis.sismember('run_immediately', entry.key) + assert stored.is_due()[0] + outgoing = next(stored) + assert 'bootstrap' not in outgoing.kwargs + assert not outgoing._strtobool(outgoing.run_immediately) + finished = load(entry) + assert not finished._strtobool(finished.run_immediately) + assert not app.redbeat_redis.sismember('run_immediately', entry.key) + + +def test_repeated_deferred_requests_keep_earliest_due_and_latest_payload(app): + entry = create_entry(app) + for index, seconds in enumerate((20, 40, 10)): + current = load(entry) + current.kwargs = {'revision': index} + current.request_run(NOW + timedelta(seconds=seconds)) + accepted_due = NOW + timedelta(seconds=min((20, 40, 10)[: index + 1])) + assert ( + app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + == accepted_due.timestamp() + ) + assert load(entry).last_run_at == accepted_due - timedelta(seconds=60) + assert load(entry)._strtobool(load(entry).run_immediately) + assert load(entry).kwargs == {'revision': 2} + assert set(app.redbeat_redis.hgetall(entry.key)) == { + 'definition', + 'meta', + 'jitter_fingerprint', + 'entry_id', + } + + +@pytest.mark.parametrize('new_interval', [60, 120]) +@pytest.mark.parametrize('request_seconds', [10, 40]) +def test_refresh_preserves_pending_first_arguments_and_earliest_deadline( + app, new_interval, request_seconds +): + entry = create_entry(app, NOW + timedelta(seconds=20), first_run_kwargs={'bootstrap': 'first'}) + entry.kwargs = {'revision': 'latest'} + entry.schedule = schedule(new_interval, app=app) + entry.request_run( + NOW + timedelta(seconds=request_seconds), + fingerprint=entry.jitter_fingerprint, + preserve_first_run_kwargs=True, + ) + stored = load(entry) + due = NOW + timedelta(seconds=min(20, request_seconds)) + assert stored.first_run_kwargs == {'bootstrap': 'first'} + assert stored.kwargs == {'revision': 'latest'} + assert stored.last_run_at + stored.schedule.run_every == due + assert stored.total_run_count == 0 + app.now = lambda: due + outgoing = next(stored) + assert outgoing.kwargs == {'revision': 'latest', 'bootstrap': 'first'} + assert load(entry).first_run_kwargs == {} + assert load(entry).total_run_count == 1 + + +def test_refresh_does_not_restore_already_consumed_first_arguments(app): + entry = create_entry(app, first_run_kwargs={'bootstrap': 'first'}) + stale = load(entry) + next(entry) + stale.request_run(NOW + timedelta(seconds=20), preserve_first_run_kwargs=True) + stored = load(entry) + assert stored.first_run_kwargs == {} + assert stored.total_run_count == 1 + app.now = lambda: NOW + timedelta(seconds=20) + assert 'bootstrap' not in next(stored).kwargs + + +@pytest.mark.parametrize('writer', ['save', 'reschedule']) +@pytest.mark.parametrize('loaded', [False, True]) +def test_legacy_immediate_write_does_not_inherit_a_managed_deadline(app, writer, loaded): + original = create_entry(app, NOW + timedelta(seconds=20)) + if loaded: + entry = load(original) + else: + entry = RedBeatSchedulerEntry(original.name, original.task, schedule(60, app=app), app=app) + entry.run_immediately = True + getattr(entry, writer)() + stored = load(original) + assert entry.jitter_fingerprint is None + assert stored.jitter_fingerprint is None + assert stored.entry_id == original.entry_id + assert stored.is_due()[0] + next(stored) + assert load(original).last_run_at == NOW + assert load(original).total_run_count == 1 + + +def test_definition_update_preserves_complete_pending_state(app): + entry = create_entry(app) + entry.request_run(NOW + timedelta(seconds=20)) + before = app.redbeat_redis.hgetall(entry.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + entry.kwargs = {'value': 'updated'} + entry.run_immediately = True + entry.update_definition() + after = app.redbeat_redis.hgetall(entry.key) + assert after['meta'] == before['meta'] + assert after['jitter_fingerprint'] == before['jitter_fingerprint'] + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) == score + assert load(entry)._strtobool(load(entry).run_immediately) + + +@pytest.mark.parametrize('run_immediately', [False, True]) +@pytest.mark.parametrize('loaded_request', [False, True]) +def test_new_request_survives_older_reservation(app, run_immediately, loaded_request): + entry = create_entry(app) + if loaded_request: + entry.request_run(NOW) + stale = load(entry) + current = load(entry) + current.kwargs = {'value': 'new'} + due = NOW if run_immediately else NOW + timedelta(seconds=20) + current.request_run(due, run_immediately=run_immediately) + before = app.redbeat_redis.hgetall(entry.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + with pytest.raises(ValueError): + next(stale) + after = app.redbeat_redis.hgetall(entry.key) + assert after == before + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) == score + assert load(entry).total_run_count == 0 + app.now = lambda: NOW + timedelta(seconds=20) + assert load(entry).is_due()[0] + next(load(entry)) + assert not load(entry)._strtobool(load(entry).run_immediately) + assert load(entry).total_run_count == 1 + + +def test_identical_requested_runs_can_coalesce_without_additional_state(app): + entry = create_entry(app, kwargs={'value': 'same'}) + due = NOW + timedelta(seconds=20) + entry.request_run(due) + stale = load(entry) + load(entry).request_run(due) + app.now = lambda: due + + next(stale) + stored = load(entry) + + assert stored.last_run_at == due + assert stored.total_run_count == 1 + assert not stored._strtobool(stored.run_immediately) + assert set(app.redbeat_redis.hgetall(entry.key)) == { + 'definition', + 'meta', + 'jitter_fingerprint', + 'entry_id', + } + + +@pytest.mark.parametrize('update_definition', [False, True]) +def test_boolean_enabled_flag_remains_reservable_after_request_reload(app, update_definition): + entry = create_entry(app) + entry.enabled = True + entry.request_run(NOW, run_immediately=True) + if update_definition: + current = load(entry) + current.enabled = True + current.kwargs = {'value': 'latest'} + current.update_definition() + current = load(entry) + + assert current.is_due()[0] + outgoing = next(current) + stored = load(entry) + + assert stored.total_run_count == 1 + assert stored._strtobool(stored.enabled) + assert not stored._strtobool(stored.run_immediately) + assert outgoing.kwargs == ({'value': 'latest'} if update_definition else {}) + + +@pytest.mark.parametrize('reload_request', [False, True]) +@pytest.mark.parametrize('enabled', [True, 'true', 'True']) +def test_request_reservation_compares_the_persisted_payload_representation( + app, reload_request, enabled +): + entry = create_entry(app, total_run_count=4) + entry.args = ('argument',) + entry.kwargs = {'values': (1, 2), 'observed_at': NOW} + entry.enabled = enabled + due = NOW + timedelta(seconds=20) + entry.request_run(due) + current = load(entry) if reload_request else entry + app.now = lambda: due + + assert current.is_due()[0] + next(current) + stored = load(entry) + + assert stored.args == ['argument'] + assert stored.kwargs == {'values': [1, 2], 'observed_at': NOW} + assert stored.last_run_at == due + assert stored.total_run_count == 5 + assert not stored._strtobool(stored.run_immediately) + + +def test_disabled_entry_does_not_run_a_mature_request(app): + entry = create_entry(app, enabled=False) + entry.request_run(NOW, run_immediately=True) + assert load(entry).is_due() == (False, 5.0) + + +def test_immediate_request_preserves_run_count(app): + entry = create_entry(app, total_run_count=9) + entry.request_run(NOW, run_immediately=True) + assert load(entry).last_run_at == NOW - timedelta(seconds=60) + assert load(entry).total_run_count == 9 + assert load(entry).is_due()[0] + next(load(entry)) + assert load(entry).last_run_at == NOW + assert load(entry).total_run_count == 10 + + +def test_request_can_apply_new_interval_and_policy_together(app): + entry = create_entry(app) + entry.schedule = schedule(120, app=app) + due = NOW + timedelta(seconds=20) + with pytest.raises(ValueError, match='interval'): + entry.request_run(due) + entry.request_run(due, fingerprint='new-policy') + stored = load(entry) + assert stored.schedule.run_every == timedelta(seconds=120) + assert stored.jitter_fingerprint == 'new-policy' + app.now = lambda: due + next(stored) + assert ( + app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + == (due + timedelta(seconds=120)).timestamp() + ) + + +def test_request_watch_conflict_rechecks_immediate_priority(app): + entry = create_entry(app) + immediate = load(entry) + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + attempts = [] + + def conflict_once(pipe, *args, **kwargs): + attempts.append(True) + if len(attempts) == 1: + with patch.object(pipeline_class, 'execute', execute): + immediate.request_run(NOW, run_immediately=True) + return execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', conflict_once): + entry.request_run(NOW + timedelta(seconds=20)) + assert len(attempts) == 2 + assert load(entry)._strtobool(load(entry).run_immediately) + assert load(entry).last_run_at == NOW - timedelta(seconds=60) + assert load(entry).is_due()[0] + + +def test_request_stops_after_three_conflicts_and_does_not_retry_missing_entry(app): + entry = create_entry(app) + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + attempts = [] + + def conflict(pipe, *args, **kwargs): + attempts.append(True) + app.redbeat_redis.hset(entry.key, 'concurrent_value', str(len(attempts))) + return execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', conflict): + with pytest.raises(WatchError): + entry.request_run(NOW, run_immediately=True) + assert len(attempts) == 3 + assert not load(entry)._strtobool(load(entry).run_immediately) + entry.delete() + with patch.object(pipeline_class, 'execute') as commit: + with pytest.raises(KeyError): + entry.request_run(NOW, run_immediately=True) + commit.assert_not_called() diff --git a/tests/test_managed_timing.py b/tests/test_managed_timing.py new file mode 100644 index 00000000..771e679d --- /dev/null +++ b/tests/test_managed_timing.py @@ -0,0 +1,185 @@ +from datetime import timedelta, timezone +from unittest.mock import patch +from zoneinfo import ZoneInfo + +import pytest +from celery.schedules import schedule + +from redbeat.decoder import to_timestamp +from redbeat.schedulers import RedBeatScheduler, RedBeatSchedulerEntry +from tests.test_jitter_concurrent_updates import app as timing_app +from tests.test_jitter_concurrent_updates import load +from tests.test_jitter_integration import NOW +from tests.test_jitter_integration import app as redis_app # noqa: F401 + +app = timing_app + + +@pytest.mark.parametrize( + 'interval,due', + [ + (0.5, NOW + timedelta(microseconds=1)), + (1.5, NOW + timedelta(seconds=2, microseconds=250000)), + (60, NOW.replace(microsecond=999999).astimezone(timezone(timedelta(hours=5.5)))), + (60, NOW.astimezone(timezone(timedelta(hours=-3.5)))), + (3600, NOW.replace(month=3, day=8, hour=7).astimezone(ZoneInfo('America/New_York'))), + (3600, NOW.replace(month=11, day=1, hour=6).astimezone(ZoneInfo('America/New_York'))), + ], + ids=['subsecond', 'fractional', 'east', 'west', 'spring-forward', 'fall-back'], +) +def test_managed_first_due_preserves_instant_across_reload_and_recurrence(app, interval, due): + utc_due = due.astimezone(timezone.utc) + interval = timedelta(seconds=interval) + app.now = lambda: utc_due - timedelta(seconds=1) + initial = RedBeatSchedulerEntry( + 'generic-timing', 'tasks.example', schedule(interval, app=app), app=app + ).save_with_first_due(due, 'library-policy') + initial.kwargs = {'revision': 'new'} + initial.update_definition() + stored = load(initial) + assert stored.last_run_at == utc_due - interval + assert stored.last_run_at.tzinfo == timezone.utc + assert stored.schedule.run_every == interval + assert stored.total_run_count == 0 + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) == to_timestamp(due) + + scheduler = RedBeatScheduler(app, lazy=True, max_interval=7200) + try: + with patch.object(app, 'send_task') as publish: + for deadline in (utc_due, utc_due + interval): + app.now = lambda: deadline - timedelta(microseconds=1) + scheduler.tick() + publish.assert_not_called() + app.now = lambda: deadline + scheduler.tick() + publish.assert_called_once() + assert publish.call_args.args[2] == {'revision': 'new'} + publish.reset_mock() + assert load(initial).total_run_count == 2 + assert load(initial).last_run_at == utc_due + interval + finally: + scheduler.close() + + +def test_fractional_requested_due_preserves_earliest_request_and_latest_payload(app): + initial = RedBeatSchedulerEntry( + 'generic-request', 'tasks.example', schedule(1.5, app=app), app=app + ).save_with_first_due(NOW, 'library-policy') + next(initial) + due = NOW + timedelta(seconds=20, microseconds=250000) + for seconds, revision in ((0, 'first'), (10, 'latest')): + current = load(initial) + current.kwargs = {'revision': revision} + current.request_run( + (due + timedelta(seconds=seconds)).astimezone(timezone(timedelta(hours=5.5))) + ) + stored = load(initial) + assert stored.last_run_at == due - timedelta(seconds=1.5) + assert stored.last_run_at.tzinfo == timezone.utc + assert stored.kwargs == {'revision': 'latest'} + scheduler = RedBeatScheduler(app, lazy=True, max_interval=60) + try: + with patch.object(app, 'send_task') as publish: + app.now = lambda: due - timedelta(microseconds=1) + scheduler.tick() + publish.assert_not_called() + app.now = lambda: due + scheduler.tick() + publish.assert_called_once() + assert load(initial).total_run_count == 2 + assert load(initial).last_run_at == due + assert not load(initial)._strtobool(load(initial).run_immediately) + finally: + scheduler.close() + + +@pytest.mark.parametrize('urgent_first', [False, True]) +def test_fractional_urgent_request_wins_in_either_order(app, urgent_first): + initial = RedBeatSchedulerEntry( + 'generic-urgent', 'tasks.example', schedule(1.5, app=app), app=app + ).save_with_first_due(NOW, 'library-policy') + due = NOW + timedelta(microseconds=125000) + app.now = lambda: due + for urgent in (urgent_first, not urgent_first): + load(initial).request_run( + due if urgent else due + timedelta(seconds=20.25), run_immediately=urgent + ) + stored = load(initial) + assert stored.last_run_at == due - timedelta(seconds=1.5) + app.now = lambda: due - timedelta(microseconds=1) + assert not stored.is_due()[0] + app.now = lambda: due + assert stored.is_due()[0] + next(stored) + assert load(initial).last_run_at == due + assert load(initial).total_run_count == 1 + assert not load(initial)._strtobool(load(initial).run_immediately) + + +@pytest.mark.parametrize('due', [NOW.replace(tzinfo=None), None]) +def test_invalid_requested_due_keeps_saved_state(app, due): + initial = RedBeatSchedulerEntry( + 'invalid-request', 'tasks.example', schedule(1.5, app=app), app=app + ).save_with_first_due(NOW, 'library-policy') + before = app.redbeat_redis.hgetall(initial.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) + with pytest.raises(ValueError, match='timezone-aware'): + initial.request_run(due) + assert app.redbeat_redis.hgetall(initial.key) == before + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) == score + + +def test_naive_following_deadline_keeps_current_run_and_ordinary_recurrence(app): + initial = RedBeatSchedulerEntry( + 'invalid-policy', 'tasks.example', schedule(1.5, app=app), app=app + ).save_with_first_due(NOW, 'library-policy') + app.conf.redbeat_entry_policy = lambda following: ( + NOW.replace(tzinfo=None) + timedelta(seconds=3), + 'rejected-policy', + ) + outgoing = next(initial) + assert outgoing.last_run_at == NOW + assert load(initial).last_run_at == NOW + assert load(initial).total_run_count == 1 + assert load(initial).jitter_fingerprint == 'library-policy' + app.now = lambda: NOW + timedelta(seconds=1.5) + assert load(initial).is_due()[0] + + +@pytest.mark.parametrize('managed', [False, True]) +def test_following_policy_normalizes_fractional_due_and_keeps_current_run(app, managed): + initial = RedBeatSchedulerEntry( + 'generic-policy', 'tasks.example', schedule(1.5, app=app), app=app + ) + if managed: + initial.save_with_first_due(NOW, 'library-policy') + else: + initial.save() + due = NOW + timedelta(seconds=3, microseconds=250000) + + def policy(entry): + if entry.jitter_fingerprint != 'library-policy-two': + return due.astimezone(timezone(timedelta(hours=-3.5))), 'library-policy-two' + return None + + app.conf.redbeat_entry_policy = policy + outgoing = next(load(initial)) + assert outgoing.last_run_at == NOW + assert load(initial).total_run_count == 1 + assert load(initial).last_run_at == due - timedelta(seconds=1.5) + assert load(initial).last_run_at.tzinfo == timezone.utc + assert load(initial).jitter_fingerprint == 'library-policy-two' + scheduler = RedBeatScheduler(app, lazy=True, max_interval=60) + try: + with patch.object(app, 'send_task') as publish: + for deadline in (due, due + timedelta(seconds=1.5)): + app.now = lambda: deadline - timedelta(microseconds=1) + scheduler.tick() + publish.assert_not_called() + app.now = lambda: deadline + scheduler.tick() + publish.assert_called_once() + publish.reset_mock() + assert load(initial).total_run_count == 3 + finally: + scheduler.close() diff --git a/tests/test_managed_write_efficiency.py b/tests/test_managed_write_efficiency.py new file mode 100644 index 00000000..b9b2cff6 --- /dev/null +++ b/tests/test_managed_write_efficiency.py @@ -0,0 +1,174 @@ +import json +from datetime import timedelta +from unittest.mock import patch + +import pytest + +from redbeat.decoder import RedBeatJSONEncoder +from tests.test_jitter_concurrent_updates import app as efficiency_app +from tests.test_jitter_concurrent_updates import create_entry, load +from tests.test_jitter_integration import NOW +from tests.test_jitter_integration import app as redis_app # noqa: F401 + +app = efficiency_app + + +@pytest.mark.parametrize('run_immediately', [False, True]) +@pytest.mark.parametrize('changed_policy', [False, True]) +def test_request_writes_fingerprint_only_when_the_applied_policy_changes( + app, run_immediately, changed_policy +): + entry = create_entry(app) + fingerprint = 'new-policy' if changed_policy else entry.jitter_fingerprint + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + commands = [] + + def record(pipe, *args, **kwargs): + commands.extend(command for command, _ in pipe.command_stack) + return execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', record): + entry.request_run( + NOW if run_immediately else NOW + timedelta(seconds=20), + run_immediately=run_immediately, + fingerprint=fingerprint, + ) + + fingerprint_writes = [ + command for command in commands if command[:3] == ('HSET', entry.key, 'jitter_fingerprint') + ] + assert len(fingerprint_writes) == int(changed_policy) + stored = load(entry) + assert stored.jitter_fingerprint == fingerprint + assert stored._strtobool(stored.run_immediately) + due = NOW if run_immediately else NOW + timedelta(seconds=20) + assert stored.last_run_at == due - timedelta(seconds=60) + + +@pytest.mark.parametrize('pending', [False, True]) +@pytest.mark.parametrize( + 'kwargs', + [{}, {'payload': {'__type__': 'custom', 'value': 'unchanged'}}], + ids=['ordinary', 'custom-type'], +) +def test_identical_definition_keeps_pending_state_without_writing(app, pending, kwargs): + entry = create_entry(app, first_run_kwargs={'bootstrap': 'first'}, kwargs=kwargs) + if pending: + entry.request_run(NOW + timedelta(seconds=20)) + before = app.redbeat_redis.hgetall(entry.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + pipeline_class = type(app.redbeat_redis.pipeline()) + + with patch.object(pipeline_class, 'execute') as execute: + entry.update_definition() + + execute.assert_not_called() + assert app.redbeat_redis.hgetall(entry.key) == before + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) == score + + +def test_changed_definition_still_writes_and_preserves_pending_request(app): + entry = create_entry(app, kwargs={'value': 'old'}) + entry.request_run(NOW + timedelta(seconds=20)) + before = app.redbeat_redis.hgetall(entry.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) + entry.kwargs = {'value': 'new'} + pipeline_class = type(app.redbeat_redis.pipeline()) + execute = pipeline_class.execute + commands = [] + + def record(pipe, *args, **kwargs): + commands.extend(command for command, _ in pipe.command_stack) + return execute(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', record): + entry.update_definition() + + assert len(commands) == 1 + assert commands[0][:3] == ('HSET', entry.key, 'definition') + after = app.redbeat_redis.hgetall(entry.key) + assert after['definition'] != before['definition'] + assert {field: value for field, value in after.items() if field != 'definition'} == { + field: value for field, value in before.items() if field != 'definition' + } + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, entry.key) == score + assert load(entry).kwargs == {'value': 'new'} + + +@pytest.mark.parametrize('field', ['args', 'kwargs']) +@pytest.mark.parametrize('previous,updated', [(True, 1), (1, 1.0)]) +def test_definition_update_preserves_argument_type_changes(app, field, previous, updated): + original_value = [previous] if field == 'args' else {'value': previous} + entry = create_entry(app, **{field: original_value}) + setattr(entry, field, [updated] if field == 'args' else {'value': updated}) + + entry.update_definition() + + stored_value = getattr(load(entry), field) + value = stored_value[0] if field == 'args' else stored_value['value'] + assert value == updated + assert type(value) is type(updated) + + +@pytest.mark.parametrize('changed_state', ['policy', 'missing']) +def test_identical_definition_still_rejects_incompatible_stored_state(app, changed_state): + entry = create_entry(app) + if changed_state == 'missing': + entry.delete() + error = KeyError + else: + app.redbeat_redis.hset(entry.key, 'jitter_fingerprint', json.dumps('changed')) + error = ValueError + before = app.redbeat_redis.hgetall(entry.key) + pipeline_class = type(app.redbeat_redis.pipeline()) + + with patch.object(pipeline_class, 'execute') as execute: + with pytest.raises(error): + entry.update_definition() + + execute.assert_not_called() + assert app.redbeat_redis.hgetall(entry.key) == before + + +def test_identical_definition_rejects_identical_timing_same_key_replacement(app): + stale = create_entry(app) + stale.delete() + replacement = create_entry(app) + before = app.redbeat_redis.hgetall(replacement.key) + pipeline_class = type(app.redbeat_redis.pipeline()) + + with patch.object(pipeline_class, 'execute') as execute: + with pytest.raises(KeyError): + stale.update_definition() + + execute.assert_not_called() + assert app.redbeat_redis.hgetall(replacement.key) == before + + +def test_noop_definition_does_not_replace_a_concurrent_payload_update(app): + entry = create_entry(app, kwargs={'value': 'old'}) + pipeline_class = type(app.redbeat_redis.pipeline()) + hget = pipeline_class.hget + changed = [] + + def update_after_read(pipe, *args, **kwargs): + value = hget(pipe, *args, **kwargs) + if not changed and args == (entry.key, 'definition'): + definition = entry.decode_definition(value) + definition['kwargs'] = {'value': 'new'} + app.redbeat_redis.hset( + entry.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder) + ) + changed.append(True) + return value + + with ( + patch.object(pipeline_class, 'hget', update_after_read), + patch.object(pipeline_class, 'execute') as execute, + ): + entry.update_definition() + + execute.assert_not_called() + assert changed == [True] + assert load(entry).kwargs == {'value': 'new'} diff --git a/tests/test_persistence_parity.py b/tests/test_persistence_parity.py new file mode 100644 index 00000000..a2f0adc2 --- /dev/null +++ b/tests/test_persistence_parity.py @@ -0,0 +1,163 @@ +import json +from datetime import timedelta + +import pytest +from celery.beat import ScheduleEntry +from celery.schedules import schedule + +from redbeat.decoder import RedBeatJSONDecoder, RedBeatJSONEncoder +from redbeat.schedulers import RedBeatSchedulerEntry +from tests.test_jitter_concurrent_updates import app as parity_app +from tests.test_jitter_integration import NOW +from tests.test_jitter_integration import app as redis_app # noqa: F401 + +app = parity_app + + +def original_write(entry, operation): + if operation in ('reserve', 'reserve_without_count'): + outgoing = ScheduleEntry._next_instance(entry, last_run_at=entry.app.now()) + if operation == 'reserve_without_count': + outgoing.total_run_count = entry.total_run_count + metadata = { + 'last_run_at': outgoing.last_run_at, + 'total_run_count': outgoing.total_run_count, + } + with entry.app.redbeat_redis.pipeline() as pipe: + pipe.hset(entry.key, 'meta', json.dumps(metadata, cls=RedBeatJSONEncoder)) + pipe.zadd(entry.app.redbeat_conf.schedule_key, {entry.key: outgoing.score}) + pipe.execute() + return outgoing + + reset = operation == 'reschedule' + if reset: + entry.last_run_at = entry.app.now() + definition = { + 'name': entry.name, + 'task': entry.task, + 'args': entry.args, + 'kwargs': entry.kwargs, + 'options': entry.options, + 'schedule': entry.schedule, + 'enabled': entry.enabled, + 'run_immediately': entry.run_immediately, + } + if reset: + definition['target'] = entry.target + if entry.first_run_kwargs: + definition['first_run_kwargs'] = dict(entry.first_run_kwargs) + metadata = {'last_run_at': entry.last_run_at} + with entry.app.redbeat_redis.pipeline() as pipe: + pipe.hset(entry.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder)) + if reset: + pipe.hset(entry.key, 'meta', json.dumps(metadata, cls=RedBeatJSONEncoder)) + else: + pipe.hsetnx(entry.key, 'meta', json.dumps(metadata, cls=RedBeatJSONEncoder)) + pipe.zadd(entry.app.redbeat_conf.schedule_key, {entry.key: entry.score}) + if entry._strtobool(entry.run_immediately): + pipe.sadd('run_immediately', entry.key) + pipe.execute() + return None + + +def prepared_entry(app, enabled, immediate): + entry = RedBeatSchedulerEntry( + 'persistence-parity', + 'tasks.test', + schedule(210, app=app), + app=app, + last_run_at=NOW - timedelta(seconds=210), + kwargs={'value': 'old'}, + ) + client = app.redbeat_redis + client.delete(entry.key) + client.zrem(app.redbeat_conf.schedule_key, entry.key) + client.srem('run_immediately', entry.key) + original_write(entry, 'save') + client.hset( + entry.key, + mapping={ + 'meta': json.dumps( + {'last_run_at': entry.last_run_at, 'total_run_count': 7}, + cls=RedBeatJSONEncoder, + ), + 'owner_note': 'keep this independent field', + }, + ) + if not immediate: + client.sadd('run_immediately', entry.key) + entry = RedBeatSchedulerEntry.from_key(entry.key, app=app) + entry.args = ['changed-argument'] + entry.kwargs = {'value': 'new', 'nested': {'revision': 2}} + entry.options = {'queue': 'parity-queue', 'expires': 120} + entry.target = 'parity-owner' + entry.enabled = str(enabled) + entry.run_immediately = str(immediate) + entry.first_run_kwargs = {'bootstrap': 'first-invocation'} + return entry + + +def persisted_state(entry, outgoing): + client = entry.app.redbeat_redis + fields = client.hgetall(entry.key) + for field in ('definition', 'meta'): + if field in fields: + fields[field] = json.loads(fields[field], cls=RedBeatJSONDecoder) + invocation = None + if outgoing is not None: + invocation = { + field: getattr(outgoing, field) + for field in ( + 'name', + 'task', + 'args', + 'kwargs', + 'options', + 'schedule', + 'target', + 'enabled', + 'run_immediately', + 'first_run_kwargs', + 'last_run_at', + 'total_run_count', + ) + } + return ( + fields, + client.zscore(entry.app.redbeat_conf.schedule_key, entry.key), + client.sismember('run_immediately', entry.key), + invocation, + ) + + +@pytest.mark.parametrize( + 'operation', + ['save', 'reschedule', 'guarded_save', 'reserve', 'reserve_without_count'], +) +@pytest.mark.parametrize('enabled', [False, True]) +@pytest.mark.parametrize('immediate', [False, True]) +@pytest.mark.parametrize('microseconds', [0, 654321]) +def test_ordinary_persistence_matches_original_patterns( + app, operation, enabled, immediate, microseconds +): + app.now = lambda: NOW + timedelta(seconds=5, microseconds=microseconds) + reference = prepared_entry(app, enabled, immediate) + expected = persisted_state(reference, original_write(reference, operation)) + + current = prepared_entry(app, enabled, immediate) + outgoing = None + if operation == 'save': + current.save() + elif operation == 'reschedule': + current.reschedule() + elif operation == 'guarded_save': + current.save_guarded() + else: + outgoing = current.next( + last_run_at=app.now(), only_update_last_run_at=operation == 'reserve_without_count' + ) + + actual = persisted_state(current, outgoing) + assert actual == expected + assert 'jitter_fingerprint' not in actual[0] + assert actual[0]['owner_note'] == 'keep this independent field' diff --git a/tests/test_polling_jitter.py b/tests/test_polling_jitter.py new file mode 100644 index 00000000..c19d54c7 --- /dev/null +++ b/tests/test_polling_jitter.py @@ -0,0 +1,456 @@ +import json +from datetime import datetime, timedelta, timezone +from unittest.mock import patch + +import pytest +from celery import Celery +from celery.schedules import crontab, schedule +from fakeredis import FakeRedis + +from redbeat.decoder import RedBeatJSONDecoder, to_timestamp +from redbeat.schedulers import RedBeatScheduler, RedBeatSchedulerEntry + +NOW = datetime(2026, 1, 1, 12, tzinfo=timezone.utc) +FINGERPRINT = 'test-policy-v1' + + +@pytest.fixture +def app(): + result = Celery('jitter-tests', broker='memory://') + result.conf.update(redbeat_redis_url='redis://unused/0', timezone='UTC') + result.redbeat_redis = FakeRedis(decode_responses=True) + result.now = lambda: NOW + yield result + result.close() + + +def entry(app, interval=60, **kwargs): + return RedBeatSchedulerEntry( + 'first-due-test', 'tasks.test', schedule(interval, app=app), app=app, **kwargs + ) + + +@pytest.mark.parametrize('interval,first_delay', [(60, 102), (300, 356), (600, 22), (1800, 35)]) +def test_exact_first_due_roundtrip(app, interval, first_delay): + initial = entry(app, interval, total_run_count=7, run_immediately=True) + due = NOW + timedelta(seconds=first_delay) + # A stale immediate-set member must not bypass the accepted first due. + app.redbeat_redis.sadd('run_immediately', initial.key) + initial.save_with_first_due(due, FINGERPRINT) + loaded = RedBeatSchedulerEntry.from_key(initial.key, app) + raw = app.redbeat_redis.hgetall(initial.key) + assert set(raw) == {'definition', 'meta', 'jitter_fingerprint', 'entry_id'} + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) == to_timestamp(due) + assert loaded.last_run_at == due - timedelta(seconds=interval) + assert loaded.total_run_count == 7 + assert loaded.jitter_fingerprint == FINGERPRINT + assert json.loads(raw['jitter_fingerprint']) == FINGERPRINT + assert json.loads(raw['entry_id']) == loaded.entry_id == initial.entry_id + assert 'entry_id' not in json.loads(raw['definition']) + assert loaded.run_immediately == 'False' + assert not app.redbeat_redis.sismember('run_immediately', initial.key) + assert loaded.is_due()[0] is False + app.now = lambda: due - timedelta(microseconds=1) + assert loaded.is_due()[0] is False + app.now = lambda: due + assert loaded.is_due()[0] is True + + +@pytest.mark.parametrize('decode_responses', [True, False], ids=['text', 'bytes']) +def test_json_fingerprint_roundtrip_and_missing_value(app, decode_responses): + app.redbeat_redis = FakeRedis(decode_responses=decode_responses) + initial = entry(app).save() + assert RedBeatSchedulerEntry.from_key(initial.key, app).jitter_fingerprint is None + initial.delete() + + fingerprint = 'library-policy-caf\u00e9-\u03bb' + initial.save_with_first_due(NOW, fingerprint) + + raw = app.redbeat_redis.hget(initial.key, 'jitter_fingerprint') + assert json.loads(raw) == fingerprint + assert RedBeatSchedulerEntry.from_key(initial.key, app).jitter_fingerprint == fingerprint + + +def test_writes_are_grouped_in_a_transaction(app): + pipeline_class = type(app.redbeat_redis.pipeline()) + original = pipeline_class.execute + recorded = [] + + def record(pipe, *args, **kwargs): + recorded.append((pipe.transaction, list(pipe.command_stack))) + return original(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', record): + entry(app).save_with_first_due(NOW + timedelta(seconds=42), FINGERPRINT) + transaction, commands = recorded[0] + assert transaction is True + assert [command[0][0] for command in commands] == [ + 'HSET', + 'HSET', + 'HSET', + 'HSET', + 'ZADD', + 'SREM', + ] + assert [command[0][2] for command in commands[:4]] == [ + 'definition', + 'meta', + 'jitter_fingerprint', + 'entry_id', + ] + + +@pytest.mark.parametrize('state', ['legacy', 'ordinary', 'initial', 'immediate', 'both']) +def test_reservation_field_writes_remain_in_one_transaction(app, state): + initial = entry(app) + if state != 'legacy': + initial.save_with_first_due( + NOW, + FINGERPRINT, + first_run_kwargs={'bootstrap_token': 'first'} if state in ('initial', 'both') else {}, + ) + else: + initial.save() + if state in ('immediate', 'both'): + initial.run_immediately = True + initial.save() + pipeline_class = type(app.redbeat_redis.pipeline()) + original = pipeline_class.execute + recorded = [] + + def record(pipe, *args, **kwargs): + recorded.append((pipe.transaction, list(pipe.command_stack))) + return original(pipe, *args, **kwargs) + + with patch.object(pipeline_class, 'execute', record): + next(initial) + transaction, commands = recorded[0] + assert transaction is True + changes_definition = state in ('initial', 'immediate', 'both') + expected = ['HSET', 'HSET'] if changes_definition else ['HSET'] + expected += ['ZADD', 'SREM'] if state != 'legacy' else ['ZADD'] + assert [command[0][0] for command in commands] == expected + fields = [command[0][2] for command in commands if command[0][0] == 'HSET'] + assert fields == (['meta', 'definition'] if changes_definition else ['meta']) + + +def test_ordinary_managed_reservation_does_not_rewrite_definition(app): + initial = entry(app, kwargs={'value': 'unchanged'}).save_with_first_due(NOW, FINGERPRINT) + definition = json.loads(app.redbeat_redis.hget(initial.key, 'definition')) + # Different whitespace makes an unnecessary definition rewrite visible. + raw_definition = json.dumps(definition, indent=2) + app.redbeat_redis.hset(initial.key, 'definition', raw_definition) + + next(RedBeatSchedulerEntry.from_key(initial.key, app)) + + assert app.redbeat_redis.hget(initial.key, 'definition') == raw_definition + stored = RedBeatSchedulerEntry.from_key(initial.key, app) + assert stored.last_run_at == NOW + assert stored.total_run_count == 1 + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) == to_timestamp( + NOW + timedelta(seconds=60) + ) + + +def test_reservation_keeps_existing_false_flag_normalization(app): + initial = entry(app).save_with_first_due(NOW, FINGERPRINT) + initial.run_immediately = False + initial.save() + + next(RedBeatSchedulerEntry.from_key(initial.key, app)) + + assert RedBeatSchedulerEntry.from_key(initial.key, app).run_immediately == 'False' + + +@pytest.mark.parametrize( + 'due', + [ + NOW.replace(tzinfo=None), + None, + ], +) +def test_reject_invalid_due_without_writes(app, due): + initial = entry(app) + with pytest.raises(ValueError, match='timezone-aware'): + initial.save_with_first_due(due, FINGERPRINT) + assert app.redbeat_redis.dbsize() == 0 + + +@pytest.mark.parametrize('interval', [0, -1]) +def test_reject_invalid_interval_without_writes(app, interval): + with pytest.raises(ValueError, match='interval'): + entry(app, interval).save_with_first_due(NOW, FINGERPRINT) + assert app.redbeat_redis.dbsize() == 0 + + +@pytest.mark.parametrize('fingerprint', [None, '', False, 1]) +def test_reject_invalid_fingerprint_without_writes(app, fingerprint): + initial = entry(app) + with pytest.raises(ValueError, match='fingerprint'): + initial.save_with_first_due(NOW, fingerprint) + assert app.redbeat_redis.dbsize() == 0 + + +def test_reject_noninterval_and_relative_schedule(app): + for value in (crontab(), schedule(60, relative=True, app=app)): + initial = entry(app) + initial.schedule = value + with pytest.raises(ValueError): + initial.save_with_first_due(NOW, FINGERPRINT) + + +def test_existing_entry_not_overwritten(app): + initial = entry(app).save_with_first_due(NOW + timedelta(seconds=20), FINGERPRINT) + before = app.redbeat_redis.hgetall(initial.key) + with pytest.raises(ValueError): + initial.save_with_first_due(NOW + timedelta(seconds=50), FINGERPRINT) + assert app.redbeat_redis.hgetall(initial.key) == before + + +def test_first_due_refuses_orphan_hash_instead_of_repairing_it(app): + initial = entry(app) + app.redbeat_redis.hset(initial.key, 'meta', '{}') + before = app.redbeat_redis.hgetall(initial.key) + with pytest.raises(ValueError, match='existing schedule hash'): + initial.save_with_first_due(NOW, FINGERPRINT) + assert app.redbeat_redis.hgetall(initial.key) == before + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) is None + + +def test_definition_only_preserves_due_metadata_and_extra_hash_fields(app): + initial = entry( + app, + kwargs={'job_id': 'job-01'}, + options={'expires': 60, 'link': ['callback']}, + ) + initial.save_with_first_due( + NOW + timedelta(seconds=20), FINGERPRINT, first_run_kwargs={'bootstrap_token': 'first'} + ) + app.redbeat_redis.hset(initial.key, 'custom_metadata', 'preserve-me') + before = app.redbeat_redis.hgetall(initial.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) + initial.kwargs = {'job_id': 'job-01', 'revision': 'changed'} + # A local flag change must not turn this payload update into a run request. + initial.run_immediately = True + initial.update_definition() + after = app.redbeat_redis.hgetall(initial.key) + assert {key: value for key, value in before.items() if key != 'definition'} == { + key: value for key, value in after.items() if key != 'definition' + } + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) == score + loaded = RedBeatSchedulerEntry.from_key(initial.key, app) + assert loaded.kwargs['revision'] == 'changed' + assert loaded.first_run_kwargs == {'bootstrap_token': 'first'} + assert 'bootstrap_token' not in loaded.kwargs + assert loaded.options == {'expires': 60, 'link': ['callback']} + assert loaded.run_immediately == 'False' + + +def test_definition_update_cannot_recreate_or_rephase(app): + initial = entry(app).save_with_first_due(NOW + timedelta(seconds=20), FINGERPRINT) + initial.schedule = schedule(120, app=app) + with pytest.raises(ValueError, match='interval'): + initial.update_definition() + initial.delete() + with pytest.raises(KeyError): + initial.update_definition() + assert not app.redbeat_redis.exists(initial.key) + + +@pytest.mark.parametrize('fingerprint', [None, '', 'changed-policy']) +def test_definition_update_refuses_missing_or_changed_policy(app, fingerprint): + initial = entry(app).save_with_first_due(NOW + timedelta(seconds=20), FINGERPRINT) + if fingerprint is None: + app.redbeat_redis.hdel(initial.key, 'jitter_fingerprint') + else: + app.redbeat_redis.hset(initial.key, 'jitter_fingerprint', json.dumps(fingerprint)) + before = app.redbeat_redis.hgetall(initial.key) + score = app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) + initial.kwargs = {'updated': True} + with pytest.raises(ValueError, match='policy changed'): + initial.update_definition() + assert app.redbeat_redis.hgetall(initial.key) == before + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, initial.key) == score + + +def test_reservation_keeps_outgoing_context_only(app): + initial = entry(app, kwargs={'job_id': 'job-01'}) + due = NOW + timedelta(seconds=20) + initial.save_with_first_due(due, FINGERPRINT, first_run_kwargs={'bootstrap_token': 'first'}) + copied = RedBeatSchedulerEntry(**dict(initial)) + assert copied.jitter_fingerprint == FINGERPRINT + app.now = lambda: due + scheduler = RedBeatScheduler(app, lazy=True) + outgoing = scheduler.reserve(initial) + stored = RedBeatSchedulerEntry.from_key(initial.key, app) + assert outgoing.kwargs['bootstrap_token'] == 'first' + assert outgoing.first_run_kwargs == {} + assert stored.first_run_kwargs == {} + assert 'bootstrap_token' not in stored.kwargs + assert initial.first_run_kwargs == {'bootstrap_token': 'first'} + assert 'bootstrap_token' not in initial.kwargs + assert outgoing.kwargs is not initial.kwargs + assert stored.last_run_at == due + assert stored.total_run_count == 1 + assert app.redbeat_redis.zscore(app.redbeat_conf.schedule_key, stored.key) == to_timestamp( + due + timedelta(seconds=60) + ) + app.now = lambda: due + timedelta(seconds=60) + assert stored.is_due()[0] + assert 'bootstrap_token' not in next(stored).kwargs + + +def test_only_update_last_run_preserves_count(app): + initial = entry(app, total_run_count=5).save_with_first_due( + NOW + timedelta(seconds=20), FINGERPRINT + ) + assert initial.next(last_run_at=NOW, only_update_last_run_at=True).total_run_count == 5 + + +def test_managed_reservation_clears_consumed_immediate_request(app): + initial = entry(app).save_with_first_due(NOW + timedelta(seconds=20), FINGERPRINT) + initial.request_run(NOW, run_immediately=True) + loaded = RedBeatSchedulerEntry.from_key(initial.key, app) + assert loaded.is_due()[0] + outgoing = next(loaded) + stored = RedBeatSchedulerEntry.from_key(initial.key, app) + assert outgoing.last_run_at == stored.last_run_at == NOW + assert stored.total_run_count == 1 + assert stored.run_immediately == 'False' + assert not app.redbeat_redis.sismember('run_immediately', initial.key) + assert stored.jitter_fingerprint == FINGERPRINT + app.now = lambda: NOW + timedelta(seconds=1) + assert not stored.is_due()[0] + + +def test_legacy_entries_keep_ordinary_definition(app): + initial = entry(app).save() + loaded = RedBeatSchedulerEntry.from_key(initial.key, app) + assert loaded.jitter_fingerprint is None + assert 'jitter_fingerprint' not in json.loads( + app.redbeat_redis.hget(initial.key, 'definition'), cls=RedBeatJSONDecoder + ) + assert not app.redbeat_redis.hexists(initial.key, 'jitter_fingerprint') + definition = app.redbeat_redis.hget(initial.key, 'definition') + app.redbeat_redis.sadd('run_immediately', initial.key) + next(loaded) + assert not app.redbeat_redis.hexists(initial.key, 'jitter_fingerprint') + assert app.redbeat_redis.hget(initial.key, 'definition') == definition + assert app.redbeat_redis.sismember('run_immediately', initial.key) + + +def test_first_run_kwargs_override_only_the_first_invocation(app): + initial = entry(app, kwargs={'mode': 'regular', 'value': 7}).save_with_first_due( + NOW, FINGERPRINT, first_run_kwargs={'mode': 'bootstrap', 'token': 'first'} + ) + outgoing = next(initial) + stored = RedBeatSchedulerEntry.from_key(initial.key, app) + + assert outgoing.kwargs == {'mode': 'bootstrap', 'value': 7, 'token': 'first'} + assert stored.kwargs == {'mode': 'regular', 'value': 7} + assert stored.first_run_kwargs == {} + assert next(stored).kwargs == {'mode': 'regular', 'value': 7} + + +@pytest.mark.parametrize( + 'supplied,expected', + [ + (None, {'constructor_token': 'first'}), + ({'replacement_token': 'first'}, {'replacement_token': 'first'}), + ({}, {}), + ], +) +def test_first_due_selects_first_run_kwargs_without_changing_recurring_kwargs( + app, supplied, expected +): + initial = entry( + app, + kwargs={'permanent': 'keep'}, + first_run_kwargs={'constructor_token': 'first'}, + ).save_with_first_due(NOW, FINGERPRINT, first_run_kwargs=supplied) + + loaded = RedBeatSchedulerEntry.from_key(initial.key, app) + assert loaded.first_run_kwargs == expected + assert loaded.kwargs == {'permanent': 'keep'} + assert next(loaded).kwargs == {'permanent': 'keep', **expected} + assert RedBeatSchedulerEntry.from_key(initial.key, app).first_run_kwargs == {} + + +def test_managed_operations_use_subclass_definition_decoder(app): + decoded = [] + + class CustomEntry(RedBeatSchedulerEntry): + @staticmethod + def decode_definition(definition): + decoded.append(definition) + return RedBeatSchedulerEntry.decode_definition(definition) + + initial = CustomEntry( + 'custom-decoder', + 'tasks.test', + schedule(60, app=app), + app=app, + kwargs={'value': 'old'}, + ).save_with_first_due(NOW, FINGERPRINT, first_run_kwargs={'bootstrap_token': 'first'}) + + loaded = CustomEntry.from_key(initial.key, app) + assert len(decoded) == 1 + loaded.kwargs = {'value': 'new'} + loaded.update_definition() + assert len(decoded) == 2 + assert next(loaded).kwargs == {'value': 'new', 'bootstrap_token': 'first'} + assert len(decoded) == 3 + stored = json.loads(app.redbeat_redis.hget(initial.key, 'definition')) + assert stored['kwargs'] == {'value': 'new'} + assert 'first_run_kwargs' not in stored + + +@pytest.mark.parametrize('operation', ['save', 'reschedule']) +def test_first_run_kwargs_survive_existing_field_write_methods(app, operation): + initial = entry(app, first_run_kwargs={'bootstrap_token': 'first'}) + getattr(initial, operation)() + stored = RedBeatSchedulerEntry.from_key(initial.key, app) + + assert stored.first_run_kwargs == {'bootstrap_token': 'first'} + assert stored.kwargs == {} + + +def test_first_run_kwargs_can_be_cancelled_before_immediate_run(app): + initial = entry(app).save_with_first_due( + NOW + timedelta(seconds=20), FINGERPRINT, first_run_kwargs={'bootstrap_token': 'first'} + ) + initial.first_run_kwargs = {} + initial.save() + loaded = RedBeatSchedulerEntry.from_key(initial.key, app) + + assert loaded.first_run_kwargs == {} + loaded.request_run(NOW, run_immediately=True) + assert next(loaded).kwargs == {} + assert 'first_run_kwargs' not in json.loads(app.redbeat_redis.hget(initial.key, 'definition')) + + +def test_recurring_kwargs_are_not_implicitly_first_run_kwargs(app): + initial = entry(app, kwargs={'bootstrap_token': 'permanent'}).save_with_first_due( + NOW, FINGERPRINT + ) + loaded = RedBeatSchedulerEntry.from_key(initial.key, app) + + assert loaded.first_run_kwargs == {} + assert next(loaded).kwargs == {'bootstrap_token': 'permanent'} + assert RedBeatSchedulerEntry.from_key(initial.key, app).kwargs == { + 'bootstrap_token': 'permanent' + } + + +def test_first_run_and_recurring_kwargs_remain_separate(app): + initial = entry(app, kwargs={'bootstrap_token': 'first'}).save_with_first_due( + NOW, FINGERPRINT, first_run_kwargs={'other_token': 'once'} + ) + loaded = RedBeatSchedulerEntry.from_key(initial.key, app) + + assert loaded.kwargs == {'bootstrap_token': 'first'} + assert loaded.first_run_kwargs == {'other_token': 'once'} + assert next(loaded).kwargs == {'bootstrap_token': 'first', 'other_token': 'once'} + stored = RedBeatSchedulerEntry.from_key(initial.key, app) + assert stored.kwargs == {'bootstrap_token': 'first'} + assert stored.first_run_kwargs == {} diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index eeadeead..240434a2 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -10,6 +10,7 @@ from celery.schedules import schedstate, schedule from celery.utils.time import maybe_timedelta from redis import CredentialProvider +from redis.exceptions import ConnectionError, ResponseError from redbeat import RedBeatScheduler from redbeat.schedulers import ( @@ -164,7 +165,14 @@ def test_due_now(self): with patch.object(self.s, 'send_task') as send_task: sleep = self.s.tick() - send_task.assert_called_with(e.task, e.args, e.kwargs, **self.s._maybe_due_kwargs) + send_task.assert_called_once() + args, options = send_task.call_args + self.assertEqual(args, (e.task, e.args, e.kwargs)) + expected_options = dict(self.s._maybe_due_kwargs) + # Newer Celery adds a Beat-origin header. Older versions omit it. + if 'headers' in options: + expected_options['headers'] = {'celery_beat_task': True} + self.assertEqual(options, expected_options) self.assertEqual(sleep, 1.0) @@ -192,6 +200,26 @@ def test_lock_acquisition_failed_during_startup(self): with self.assertRaises(AttributeError): self.s.tick() + def test_redis_selection_errors_propagate(self): + errors = [ + ResponseError('Redis command failed'), + ConnectionError('Redis connection unavailable'), + ] + for error in errors: + with self.subTest(error=type(error).__name__): + with ( + patch.object( + RedBeatScheduler, + 'schedule', + new_callable=mock.PropertyMock, + side_effect=error, + ), + patch.object(self.s, 'maybe_due') as maybe_due, + ): + with self.assertRaises(type(error)): + self.s.tick() + maybe_due.assert_not_called() + class TestRedBeatSchedulerUpdateFromDict(RedBeatSchedulerTestBase): @patch.object(RedBeatSchedulerEntry, "from_key")