From 9852278751be3ec4f1f1fbc8443a4402295ae325 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E7=8E=89=E9=91=AB?= Date: Fri, 20 Nov 2026 17:38:00 +0800 Subject: [PATCH 1/4] Refactor automation cron time matching --- .../automations/automations_pipeline.py | 6 +-- dtable_events/automations/entities.py | 45 +++++++++---------- dtable_events/automations/general_actions.py | 1 - 3 files changed, 24 insertions(+), 28 deletions(-) diff --git a/dtable_events/automations/automations_pipeline.py b/dtable_events/automations/automations_pipeline.py index 2f07ac51..48453b35 100644 --- a/dtable_events/automations/automations_pipeline.py +++ b/dtable_events/automations/automations_pipeline.py @@ -1,8 +1,5 @@ import json -import os import time -from copy import deepcopy -from dataclasses import dataclass, field from datetime import datetime, timedelta, date from threading import Thread, Lock @@ -21,7 +18,8 @@ from dtable_events.utils.utils_metric import AUTOMATION_QUEUE_10_METRIC_HELP, AUTOMATION_QUEUE_20_METRIC_HELP, \ AUTOMATION_QUEUE_30_METRIC_HELP, REALTIME_AUTOMATION_RULES_HEARTBEAT_HELP, \ REALTIME_AUTOMATION_RULES_TRIGGERED_COUNT_HELP, SCHEDULED_AUTOMATION_RULES_TRIGGERED_COUNT_HELP, publish_metric -from dtable_events.automations.entities import AutomationResult, AutomationTask, QUEUE_AUTOMATION_TASKS_10, QUEUE_AUTOMATION_TASKS_20, QUEUE_AUTOMATION_TASKS_30 +from dtable_events.automations.entities import AutomationResult, AutomationTask, \ + QUEUE_AUTOMATION_TASKS_10, QUEUE_AUTOMATION_TASKS_20, QUEUE_AUTOMATION_TASKS_30 class RateLimiter: diff --git a/dtable_events/automations/entities.py b/dtable_events/automations/entities.py index 7b1ac6f5..4ce6e616 100644 --- a/dtable_events/automations/entities.py +++ b/dtable_events/automations/entities.py @@ -8,9 +8,7 @@ PER_UPDATE = 'per_update' PER_MONTH = 'per_month' CRON_CONDITIONS = (PER_DAY, PER_WEEK, PER_MONTH) -ALL_CONDITIONS = (PER_DAY, PER_WEEK, PER_MONTH, PER_UPDATE) -CONDITION_ROWS_MODIFIED = 'rows_modified' CONDITION_ROWS_ADDED = 'rows_added' CONDITION_FILTERS_SATISFY = 'filters_satisfy' CONDITION_PERIODICALLY = 'run_periodically' @@ -44,15 +42,34 @@ def to_dict(self): def append_warning(self, warning): self.warnings.append(warning) + def is_cron_time_matched(self): + if self.run_condition not in CRON_CONDITIONS: + return False + cur_datetime = datetime.now() + cur_hour = cur_datetime.hour + cur_week_day = cur_datetime.isoweekday() + cur_month_day = cur_datetime.day + if self.run_condition == PER_DAY: + return cur_hour == self.trigger.get('notify_hour', 12) + if self.run_condition == PER_WEEK: + return cur_hour == self.trigger.get('notify_week_hour', 12) \ + and cur_week_day == self.trigger.get('notify_week_day', 7) + return cur_hour == self.trigger.get('notify_month_hour', 12) \ + and cur_month_day == self.trigger.get('notify_month_day', 1) + def can_do_actions(self): - if self.trigger.get('condition') not in (CONDITION_FILTERS_SATISFY, CONDITION_PERIODICALLY, CONDITION_ROWS_ADDED, CONDITION_PERIODICALLY_BY_CONDITION): + if self.trigger.get('condition') not in ( + CONDITION_FILTERS_SATISFY, + CONDITION_PERIODICALLY, + CONDITION_ROWS_ADDED, + CONDITION_PERIODICALLY_BY_CONDITION): return False if self.trigger.get('condition') == CONDITION_ROWS_ADDED: if self.data.get('op_type') not in ['insert_row', 'append_rows', 'insert_rows']: return False - if self.trigger.get('condition') in [CONDITION_FILTERS_SATISFY, CONDITION_ROWS_MODIFIED]: + if self.trigger.get('condition') == CONDITION_FILTERS_SATISFY: if self.data.get('op_type') not in ['modify_row', 'modify_rows', 'add_link', 'update_links', 'update_rows_links', 'remove_link', 'move_group_rows']: return False @@ -60,25 +77,7 @@ def can_do_actions(self): return True if self.run_condition in CRON_CONDITIONS: - cur_datetime = datetime.now() - cur_hour = cur_datetime.hour - cur_week_day = cur_datetime.isoweekday() - cur_month_day = cur_datetime.day - if self.run_condition == PER_DAY: - trigger_hour = self.trigger.get('notify_hour', 12) - if cur_hour != trigger_hour: - return False - elif self.run_condition == PER_WEEK: - trigger_hour = self.trigger.get('notify_week_hour', 12) - trigger_day = self.trigger.get('notify_week_day', 7) - if cur_hour != trigger_hour or cur_week_day != trigger_day: - return False - else: - trigger_hour = self.trigger.get('notify_month_hour', 12) - trigger_day = self.trigger.get('notify_month_day', 1) - if cur_hour != trigger_hour or cur_month_day != trigger_day: - return False - return True + return self.is_cron_time_matched() return False diff --git a/dtable_events/automations/general_actions.py b/dtable_events/automations/general_actions.py index 9eafd031..c5112a2c 100644 --- a/dtable_events/automations/general_actions.py +++ b/dtable_events/automations/general_actions.py @@ -34,7 +34,6 @@ CONDITION_ROWS_MODIFIED = 'rows_modified' CONDITION_ROWS_ADDED = 'rows_added' CONDITION_FILTERS_SATISFY = 'filters_satisfy' -CONDITION_NEAR_DEADLINE = 'near_deadline' CONDITION_PERIODICALLY = 'run_periodically' CONDITION_PERIODICALLY_BY_CONDITION = 'run_periodically_by_condition' From 2363b39eb150c022c9fbafedd8d61cb327269c8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E7=8E=89=E9=91=AB?= Date: Fri, 20 Nov 2026 18:31:12 +0800 Subject: [PATCH 2/4] Use configured timezone for automation cron scheduling and matching --- dtable_events/automations/automations_pipeline.py | 4 ++-- dtable_events/automations/entities.py | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/dtable_events/automations/automations_pipeline.py b/dtable_events/automations/automations_pipeline.py index 48453b35..5a3e843c 100644 --- a/dtable_events/automations/automations_pipeline.py +++ b/dtable_events/automations/automations_pipeline.py @@ -7,7 +7,7 @@ from sqlalchemy import text from dtable_events.app.config import INNER_DTABLE_WEB_SERVICE_URL, AUTOMATION_RATE_LIMIT_PERCENT, \ - AUTOMATION_RATE_LIMIT_WINDOW_SECS, AUTOMATION_WORKERS + AUTOMATION_RATE_LIMIT_WINDOW_SECS, AUTOMATION_WORKERS, TIME_ZONE from dtable_events.app.event_redis import RedisClient from dtable_events.app.log import auto_rule_logger from dtable_events.automations.automations_stats_manager import AutomationsStatsManager @@ -327,7 +327,7 @@ def scan_rules(self): db_session.close() def scheduled_scan(self): - sched = BlockingScheduler() + sched = BlockingScheduler(timezone=TIME_ZONE) # fire at every hour in every day of week @sched.scheduled_job('cron', day_of_week='*', hour='*', misfire_grace_time=600) def timed_job(): diff --git a/dtable_events/automations/entities.py b/dtable_events/automations/entities.py index 4ce6e616..b814cbcd 100644 --- a/dtable_events/automations/entities.py +++ b/dtable_events/automations/entities.py @@ -1,6 +1,9 @@ from copy import deepcopy from datetime import datetime, date from dataclasses import dataclass, field +from zoneinfo import ZoneInfo + +from dtable_events.app.config import TIME_ZONE PER_DAY = 'per_day' @@ -45,7 +48,7 @@ def append_warning(self, warning): def is_cron_time_matched(self): if self.run_condition not in CRON_CONDITIONS: return False - cur_datetime = datetime.now() + cur_datetime = datetime.now(tz=ZoneInfo(TIME_ZONE)) cur_hour = cur_datetime.hour cur_week_day = cur_datetime.isoweekday() cur_month_day = cur_datetime.day From 85e3484fe1ed926cfc144ed40ada5ad7a97716d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E7=8E=89=E9=91=AB?= Date: Sat, 21 Nov 2026 14:38:26 +0800 Subject: [PATCH 3/4] Use local day boundaries for scheduled automation scans across DST shifts --- .../automations/automations_pipeline.py | 15 ++-- dtable_events/automations/entities.py | 11 ++- tests/test_scheduled_automation.py | 85 +++++++++++++++++++ 3 files changed, 103 insertions(+), 8 deletions(-) create mode 100644 tests/test_scheduled_automation.py diff --git a/dtable_events/automations/automations_pipeline.py b/dtable_events/automations/automations_pipeline.py index 5a3e843c..4c066423 100644 --- a/dtable_events/automations/automations_pipeline.py +++ b/dtable_events/automations/automations_pipeline.py @@ -1,7 +1,8 @@ import json import time -from datetime import datetime, timedelta, date +from datetime import datetime, timedelta, date, timezone from threading import Thread, Lock +from zoneinfo import ZoneInfo from apscheduler.schedulers.blocking import BlockingScheduler from sqlalchemy import text @@ -265,9 +266,12 @@ def scan_rules(self): OR (run_condition='per_month' AND (last_trigger_time<:per_month_check_time OR last_trigger_time IS NULL))) AND dar.is_valid=1 AND d.deleted=0 AND is_pause=0 ''' - per_day_check_time = datetime.utcnow() - timedelta(hours=23) - per_week_check_time = datetime.utcnow() - timedelta(days=6) - per_month_check_time = datetime.utcnow() - timedelta(days=27) # consider the least month-days 28 in February (the 2nd month) in common years + scheduled_at = datetime.now(tz=ZoneInfo(TIME_ZONE)) + local_day_start = scheduled_at.replace(hour=0, minute=0, second=0, microsecond=0, fold=0) + per_day_check_time = local_day_start.astimezone(timezone.utc).replace(tzinfo=None) + now_utc = scheduled_at.astimezone(timezone.utc).replace(tzinfo=None) + per_week_check_time = now_utc - timedelta(days=6) + per_month_check_time = now_utc - timedelta(days=27) # consider the least month-days 28 in February (the 2nd month) in common years db_session = self._db_session_class() try: auto_rule_logger.info('Scanning scheduled automation rules...') @@ -299,7 +303,8 @@ def scan_rules(self): org_id=rule.org_id, owner=rule.owner, data=None, - with_test=False + with_test=False, + scheduled_at=scheduled_at, ) if not automation_task.can_do_actions(): continue diff --git a/dtable_events/automations/entities.py b/dtable_events/automations/entities.py index b814cbcd..ff3fba8b 100644 --- a/dtable_events/automations/entities.py +++ b/dtable_events/automations/entities.py @@ -25,7 +25,8 @@ class AutomationTask: - def __init__(self, rule_id, run_condition, trigger, actions, dtable_uuid, org_id, owner, data, with_test, task_id=None): + def __init__(self, rule_id, run_condition, trigger, actions, dtable_uuid, org_id, owner, data, with_test, + task_id=None, scheduled_at=None): self.rule_id = rule_id self.run_condition = run_condition self.trigger = trigger @@ -37,10 +38,14 @@ def __init__(self, rule_id, run_condition, trigger, actions, dtable_uuid, org_id self.data = data self.with_test = with_test self.task_id = task_id + self.scheduled_at = scheduled_at self.warnings = [] def to_dict(self): - return {key: value for key, value in self.__dict__.items() if key not in ['trigger', 'actions']} + payload = {key: value for key, value in self.__dict__.items() if key not in ('trigger', 'actions', 'scheduled_at')} + if self.scheduled_at is not None: + payload['scheduled_at'] = self.scheduled_at.isoformat() + return payload def append_warning(self, warning): self.warnings.append(warning) @@ -48,7 +53,7 @@ def append_warning(self, warning): def is_cron_time_matched(self): if self.run_condition not in CRON_CONDITIONS: return False - cur_datetime = datetime.now(tz=ZoneInfo(TIME_ZONE)) + cur_datetime = self.scheduled_at or datetime.now(tz=ZoneInfo(TIME_ZONE)) cur_hour = cur_datetime.hour cur_week_day = cur_datetime.isoweekday() cur_month_day = cur_datetime.day diff --git a/tests/test_scheduled_automation.py b/tests/test_scheduled_automation.py new file mode 100644 index 00000000..c29089ac --- /dev/null +++ b/tests/test_scheduled_automation.py @@ -0,0 +1,85 @@ +import json +import sys +import unittest +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace +from unittest.mock import Mock, patch +from zoneinfo import ZoneInfo + +from apscheduler.schedulers.blocking import BlockingScheduler +from sqlalchemy import create_engine, text +from sqlalchemy.orm import sessionmaker + + +# File storage is not needed to scan automation rules. +with patch.dict('os.environ', {'SEATABLE_LOG_TO_STDOUT': 'true'}), patch.dict(sys.modules, { + 'seaserv': SimpleNamespace(ccnet_api=None, seafile_api=None, USE_GO_FILESERVER=False), + 'seafobj': SimpleNamespace(fs_mgr=None, commit_mgr=None, block_mgr=None), +}): + from dtable_events.automations import automations_pipeline, entities + + +class ScheduledAutomationTest(unittest.TestCase): + + def test_spring_forward_scans_daily_rules_using_local_day_boundary(self): + tz = ZoneInfo('America/New_York') + engine = create_engine('sqlite://') + self.addCleanup(engine.dispose) + redis = Mock() + stats_manager = Mock() + stats_manager.is_exceed.return_value = False + with patch.object(automations_pipeline, 'init_db_session_class', return_value=sessionmaker(bind=engine)), \ + patch.object(automations_pipeline, 'RedisClient', return_value=redis), \ + patch.object(automations_pipeline, 'AutomationsStatsManager', return_value=stats_manager), \ + patch.object(automations_pipeline, 'TIME_ZONE', tz.key), \ + patch.object(BlockingScheduler, 'start', autospec=True) as start: + pipeline = automations_pipeline.AutomationsPipeline() + pipeline.scheduled_scan() + + scheduler = start.call_args.args[0] + scan_job, = scheduler.get_jobs() + previous_run = scan_job.trigger.get_next_fire_time(None, datetime(2026, 3, 7, 8, 59, tzinfo=tz)) + current_run = scan_job.trigger.get_next_fire_time(None, datetime(2026, 3, 8, 8, 59, tzinfo=tz)) + previous_run_utc = previous_run.astimezone(timezone.utc).replace(tzinfo=None) + current_run_utc = current_run.astimezone(timezone.utc).replace(tzinfo=None) + self.assertEqual(current_run_utc - previous_run_utc, timedelta(hours=23)) + + with engine.begin() as connection: + connection.exec_driver_sql('CREATE TABLE workspaces (id INTEGER, owner TEXT, org_id INTEGER)') + connection.exec_driver_sql('CREATE TABLE dtables (uuid TEXT, workspace_id INTEGER, deleted INTEGER)') + connection.exec_driver_sql(''' + CREATE TABLE dtable_automation_rules ( + id INTEGER, run_condition TEXT, `trigger` TEXT, actions TEXT, dtable_uuid TEXT, + last_trigger_time DATETIME, is_valid INTEGER, is_pause INTEGER + ) + ''') + connection.exec_driver_sql("INSERT INTO workspaces VALUES (1, 'owner', 1)") + connection.exec_driver_sql("INSERT INTO dtables VALUES ('base', 1, 0)") + connection.execute(text(''' + INSERT INTO dtable_automation_rules + VALUES (:id, 'per_day', :trigger, '[]', 'base', :last_run, 1, 0) + '''), [ + {'id': rule_id, 'trigger': '{"rule_name":"Daily","condition":"run_periodically","notify_hour":9}', + 'last_run': last_run} + for rule_id, last_run in [ + (1, previous_run_utc), + (2, None), + (3, datetime(2026, 3, 8, 5)), # Exactly local midnight. + (4, datetime(2026, 3, 8, 4, 59)), # Still the previous local day. + ] + ]) + + clock = Mock(wraps=datetime) + clock.now.side_effect = lambda tz: current_run.astimezone(tz) + clock.utcnow.return_value = current_run_utc + with patch.object(automations_pipeline, 'TIME_ZONE', tz.key), \ + patch.object(entities, 'TIME_ZONE', tz.key), \ + patch.object(automations_pipeline, 'datetime', clock), \ + patch.object(entities, 'datetime', clock): + scan_job.func() + + queued = [(queue, json.loads(payload)) for queue, payload in (call.args for call in redis.lpush.call_args_list)] + self.assertCountEqual([payload['rule_id'] for _, payload in queued], [1, 2, 4]) + for queue, payload in queued: + self.assertEqual(queue, 'automation_tasks_20') + self.assertEqual(payload['scheduled_at'], '2026-03-08T09:00:00-04:00') From 072dab64492882b48d0f69f0eaa63641a5916430 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E7=8E=89=E9=91=AB?= Date: Mon, 23 Nov 2026 09:58:17 +0800 Subject: [PATCH 4/4] refactor: revert timezone-aware scheduled automation changes and tests --- .../automations/automations_pipeline.py | 19 ++--- dtable_events/automations/entities.py | 14 +-- tests/test_scheduled_automation.py | 85 ------------------- 3 files changed, 10 insertions(+), 108 deletions(-) delete mode 100644 tests/test_scheduled_automation.py diff --git a/dtable_events/automations/automations_pipeline.py b/dtable_events/automations/automations_pipeline.py index 4c066423..48453b35 100644 --- a/dtable_events/automations/automations_pipeline.py +++ b/dtable_events/automations/automations_pipeline.py @@ -1,14 +1,13 @@ import json import time -from datetime import datetime, timedelta, date, timezone +from datetime import datetime, timedelta, date from threading import Thread, Lock -from zoneinfo import ZoneInfo from apscheduler.schedulers.blocking import BlockingScheduler from sqlalchemy import text from dtable_events.app.config import INNER_DTABLE_WEB_SERVICE_URL, AUTOMATION_RATE_LIMIT_PERCENT, \ - AUTOMATION_RATE_LIMIT_WINDOW_SECS, AUTOMATION_WORKERS, TIME_ZONE + AUTOMATION_RATE_LIMIT_WINDOW_SECS, AUTOMATION_WORKERS from dtable_events.app.event_redis import RedisClient from dtable_events.app.log import auto_rule_logger from dtable_events.automations.automations_stats_manager import AutomationsStatsManager @@ -266,12 +265,9 @@ def scan_rules(self): OR (run_condition='per_month' AND (last_trigger_time<:per_month_check_time OR last_trigger_time IS NULL))) AND dar.is_valid=1 AND d.deleted=0 AND is_pause=0 ''' - scheduled_at = datetime.now(tz=ZoneInfo(TIME_ZONE)) - local_day_start = scheduled_at.replace(hour=0, minute=0, second=0, microsecond=0, fold=0) - per_day_check_time = local_day_start.astimezone(timezone.utc).replace(tzinfo=None) - now_utc = scheduled_at.astimezone(timezone.utc).replace(tzinfo=None) - per_week_check_time = now_utc - timedelta(days=6) - per_month_check_time = now_utc - timedelta(days=27) # consider the least month-days 28 in February (the 2nd month) in common years + per_day_check_time = datetime.utcnow() - timedelta(hours=23) + per_week_check_time = datetime.utcnow() - timedelta(days=6) + per_month_check_time = datetime.utcnow() - timedelta(days=27) # consider the least month-days 28 in February (the 2nd month) in common years db_session = self._db_session_class() try: auto_rule_logger.info('Scanning scheduled automation rules...') @@ -303,8 +299,7 @@ def scan_rules(self): org_id=rule.org_id, owner=rule.owner, data=None, - with_test=False, - scheduled_at=scheduled_at, + with_test=False ) if not automation_task.can_do_actions(): continue @@ -332,7 +327,7 @@ def scan_rules(self): db_session.close() def scheduled_scan(self): - sched = BlockingScheduler(timezone=TIME_ZONE) + sched = BlockingScheduler() # fire at every hour in every day of week @sched.scheduled_job('cron', day_of_week='*', hour='*', misfire_grace_time=600) def timed_job(): diff --git a/dtable_events/automations/entities.py b/dtable_events/automations/entities.py index ff3fba8b..4ce6e616 100644 --- a/dtable_events/automations/entities.py +++ b/dtable_events/automations/entities.py @@ -1,9 +1,6 @@ from copy import deepcopy from datetime import datetime, date from dataclasses import dataclass, field -from zoneinfo import ZoneInfo - -from dtable_events.app.config import TIME_ZONE PER_DAY = 'per_day' @@ -25,8 +22,7 @@ class AutomationTask: - def __init__(self, rule_id, run_condition, trigger, actions, dtable_uuid, org_id, owner, data, with_test, - task_id=None, scheduled_at=None): + def __init__(self, rule_id, run_condition, trigger, actions, dtable_uuid, org_id, owner, data, with_test, task_id=None): self.rule_id = rule_id self.run_condition = run_condition self.trigger = trigger @@ -38,14 +34,10 @@ def __init__(self, rule_id, run_condition, trigger, actions, dtable_uuid, org_id self.data = data self.with_test = with_test self.task_id = task_id - self.scheduled_at = scheduled_at self.warnings = [] def to_dict(self): - payload = {key: value for key, value in self.__dict__.items() if key not in ('trigger', 'actions', 'scheduled_at')} - if self.scheduled_at is not None: - payload['scheduled_at'] = self.scheduled_at.isoformat() - return payload + return {key: value for key, value in self.__dict__.items() if key not in ['trigger', 'actions']} def append_warning(self, warning): self.warnings.append(warning) @@ -53,7 +45,7 @@ def append_warning(self, warning): def is_cron_time_matched(self): if self.run_condition not in CRON_CONDITIONS: return False - cur_datetime = self.scheduled_at or datetime.now(tz=ZoneInfo(TIME_ZONE)) + cur_datetime = datetime.now() cur_hour = cur_datetime.hour cur_week_day = cur_datetime.isoweekday() cur_month_day = cur_datetime.day diff --git a/tests/test_scheduled_automation.py b/tests/test_scheduled_automation.py deleted file mode 100644 index c29089ac..00000000 --- a/tests/test_scheduled_automation.py +++ /dev/null @@ -1,85 +0,0 @@ -import json -import sys -import unittest -from datetime import datetime, timedelta, timezone -from types import SimpleNamespace -from unittest.mock import Mock, patch -from zoneinfo import ZoneInfo - -from apscheduler.schedulers.blocking import BlockingScheduler -from sqlalchemy import create_engine, text -from sqlalchemy.orm import sessionmaker - - -# File storage is not needed to scan automation rules. -with patch.dict('os.environ', {'SEATABLE_LOG_TO_STDOUT': 'true'}), patch.dict(sys.modules, { - 'seaserv': SimpleNamespace(ccnet_api=None, seafile_api=None, USE_GO_FILESERVER=False), - 'seafobj': SimpleNamespace(fs_mgr=None, commit_mgr=None, block_mgr=None), -}): - from dtable_events.automations import automations_pipeline, entities - - -class ScheduledAutomationTest(unittest.TestCase): - - def test_spring_forward_scans_daily_rules_using_local_day_boundary(self): - tz = ZoneInfo('America/New_York') - engine = create_engine('sqlite://') - self.addCleanup(engine.dispose) - redis = Mock() - stats_manager = Mock() - stats_manager.is_exceed.return_value = False - with patch.object(automations_pipeline, 'init_db_session_class', return_value=sessionmaker(bind=engine)), \ - patch.object(automations_pipeline, 'RedisClient', return_value=redis), \ - patch.object(automations_pipeline, 'AutomationsStatsManager', return_value=stats_manager), \ - patch.object(automations_pipeline, 'TIME_ZONE', tz.key), \ - patch.object(BlockingScheduler, 'start', autospec=True) as start: - pipeline = automations_pipeline.AutomationsPipeline() - pipeline.scheduled_scan() - - scheduler = start.call_args.args[0] - scan_job, = scheduler.get_jobs() - previous_run = scan_job.trigger.get_next_fire_time(None, datetime(2026, 3, 7, 8, 59, tzinfo=tz)) - current_run = scan_job.trigger.get_next_fire_time(None, datetime(2026, 3, 8, 8, 59, tzinfo=tz)) - previous_run_utc = previous_run.astimezone(timezone.utc).replace(tzinfo=None) - current_run_utc = current_run.astimezone(timezone.utc).replace(tzinfo=None) - self.assertEqual(current_run_utc - previous_run_utc, timedelta(hours=23)) - - with engine.begin() as connection: - connection.exec_driver_sql('CREATE TABLE workspaces (id INTEGER, owner TEXT, org_id INTEGER)') - connection.exec_driver_sql('CREATE TABLE dtables (uuid TEXT, workspace_id INTEGER, deleted INTEGER)') - connection.exec_driver_sql(''' - CREATE TABLE dtable_automation_rules ( - id INTEGER, run_condition TEXT, `trigger` TEXT, actions TEXT, dtable_uuid TEXT, - last_trigger_time DATETIME, is_valid INTEGER, is_pause INTEGER - ) - ''') - connection.exec_driver_sql("INSERT INTO workspaces VALUES (1, 'owner', 1)") - connection.exec_driver_sql("INSERT INTO dtables VALUES ('base', 1, 0)") - connection.execute(text(''' - INSERT INTO dtable_automation_rules - VALUES (:id, 'per_day', :trigger, '[]', 'base', :last_run, 1, 0) - '''), [ - {'id': rule_id, 'trigger': '{"rule_name":"Daily","condition":"run_periodically","notify_hour":9}', - 'last_run': last_run} - for rule_id, last_run in [ - (1, previous_run_utc), - (2, None), - (3, datetime(2026, 3, 8, 5)), # Exactly local midnight. - (4, datetime(2026, 3, 8, 4, 59)), # Still the previous local day. - ] - ]) - - clock = Mock(wraps=datetime) - clock.now.side_effect = lambda tz: current_run.astimezone(tz) - clock.utcnow.return_value = current_run_utc - with patch.object(automations_pipeline, 'TIME_ZONE', tz.key), \ - patch.object(entities, 'TIME_ZONE', tz.key), \ - patch.object(automations_pipeline, 'datetime', clock), \ - patch.object(entities, 'datetime', clock): - scan_job.func() - - queued = [(queue, json.loads(payload)) for queue, payload in (call.args for call in redis.lpush.call_args_list)] - self.assertCountEqual([payload['rule_id'] for _, payload in queued], [1, 2, 4]) - for queue, payload in queued: - self.assertEqual(queue, 'automation_tasks_20') - self.assertEqual(payload['scheduled_at'], '2026-03-08T09:00:00-04:00')