-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
fix(aci): don't fire action if there is a conflict when creating WAGS #104002
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
36b2383
don't fire action if there is a conflict when creating WAGS
cathteng 6360233
bot suggested change
cathteng 8a9757c
fix typing
cathteng cefcea2
remove unnecessary test change
cathteng 944460d
fixes from review
cathteng f99c418
naming var
cathteng File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,7 +2,7 @@ | |
| from collections import defaultdict | ||
| from datetime import datetime, timedelta | ||
|
|
||
| from django.db import models | ||
| from django.db import connection, models | ||
| from django.db.models import Case, Value, When | ||
| from django.utils import timezone | ||
|
|
||
|
|
@@ -36,6 +36,9 @@ | |
| logger = logging.getLogger(__name__) | ||
|
|
||
| EnqueuedAction = tuple[DataConditionGroup, list[DataCondition]] | ||
| UpdatedStatuses = int | ||
| CreatedStatuses = int | ||
| ConflictedStatuses = list[tuple[int, int]] # (workflow_id, action_id) | ||
|
|
||
|
|
||
| def get_workflow_action_group_statuses( | ||
|
|
@@ -71,13 +74,13 @@ def process_workflow_action_group_statuses( | |
| workflows: BaseQuerySet[Workflow], | ||
| group: Group, | ||
| now: datetime, | ||
| ) -> tuple[dict[int, int], set[int], list[WorkflowActionGroupStatus]]: | ||
| ) -> tuple[dict[int, set[int]], set[int], list[WorkflowActionGroupStatus]]: | ||
| """ | ||
| Determine which workflow actions should be fired based on their statuses. | ||
| Prepare the statuses to update and create. | ||
| """ | ||
|
|
||
| action_to_workflow_ids: dict[int, int] = {} # will dedupe because there can be only 1 | ||
| updated_action_to_workflows_ids: dict[int, set[int]] = defaultdict(set) | ||
| workflow_frequencies: dict[int, timedelta] = { | ||
| workflow.id: workflow.config.get("frequency", 0) * timedelta(minutes=1) | ||
| for workflow in workflows | ||
|
|
@@ -91,7 +94,7 @@ def process_workflow_action_group_statuses( | |
| status.workflow_id, zero_timedelta | ||
| ): | ||
| # we should fire the workflow for this action | ||
| action_to_workflow_ids[action_id] = status.workflow_id | ||
| updated_action_to_workflows_ids[action_id].add(status.workflow_id) | ||
| statuses_to_update.add(status.id) | ||
|
|
||
| missing_statuses: list[WorkflowActionGroupStatus] = [] | ||
|
|
@@ -107,31 +110,51 @@ def process_workflow_action_group_statuses( | |
| workflow_id=workflow_id, action_id=action_id, group=group, date_updated=now | ||
| ) | ||
| ) | ||
| action_to_workflow_ids[action_id] = workflow_id | ||
| updated_action_to_workflows_ids[action_id].add(workflow_id) | ||
|
|
||
| return action_to_workflow_ids, statuses_to_update, missing_statuses | ||
| return updated_action_to_workflows_ids, statuses_to_update, missing_statuses | ||
|
|
||
|
|
||
| def update_workflow_action_group_statuses( | ||
| now: datetime, statuses_to_update: set[int], missing_statuses: list[WorkflowActionGroupStatus] | ||
| ) -> None: | ||
| WorkflowActionGroupStatus.objects.filter( | ||
| ) -> tuple[UpdatedStatuses, CreatedStatuses, ConflictedStatuses]: | ||
| updated_count = WorkflowActionGroupStatus.objects.filter( | ||
| id__in=statuses_to_update, date_updated__lt=now | ||
| ).update(date_updated=now) | ||
|
|
||
| all_statuses = WorkflowActionGroupStatus.objects.bulk_create( | ||
| missing_statuses, | ||
| batch_size=1000, | ||
| ignore_conflicts=True, | ||
| ) | ||
| missing_status_pairs = [ | ||
| (status.workflow_id, status.action_id) for status in all_statuses if status.id is None | ||
| if not missing_statuses: | ||
| return updated_count, 0, [] | ||
|
|
||
| # Use raw SQL: only returns successfully created rows | ||
| # XXX: the query does not currently include batch size limit like bulk_create does | ||
| with connection.cursor() as cursor: | ||
| # Build values for batch insert | ||
| values_placeholders = [] | ||
| values_data = [] | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. bulk_create has a batch size because there are statement size limits. I don't know that we expect to hit them, I assume our expected upper end is hundreds here, but seems worth noting. |
||
| for s in missing_statuses: | ||
| values_placeholders.append("(%s, %s, %s, %s, %s)") | ||
| values_data.extend([s.workflow_id, s.action_id, s.group_id, now, now]) | ||
|
|
||
| sql = f""" | ||
| INSERT INTO workflow_engine_workflowactiongroupstatus | ||
| (workflow_id, action_id, group_id, date_added, date_updated) | ||
| VALUES {', '.join(values_placeholders)} | ||
| ON CONFLICT (workflow_id, action_id, group_id) DO NOTHING | ||
| RETURNING workflow_id, action_id | ||
| """ | ||
|
|
||
| cursor.execute(sql, values_data) | ||
| created_rows = set(cursor.fetchall()) # Only returns newly inserted rows | ||
|
|
||
| # Figure out which ones conflicted (weren't returned) | ||
| conflicted_statuses = [ | ||
| (s.workflow_id, s.action_id) | ||
| for s in missing_statuses | ||
| if (s.workflow_id, s.action_id) not in created_rows | ||
| ] | ||
| if missing_status_pairs: | ||
| logger.warning( | ||
| "Failed to create WorkflowActionGroupStatus objects", | ||
| extra={"missing_status_pairs": missing_status_pairs}, | ||
| ) | ||
|
|
||
| created_count = len(created_rows) | ||
| return updated_count, created_count, conflicted_statuses | ||
|
|
||
|
|
||
| def get_unique_active_actions( | ||
|
|
@@ -190,7 +213,7 @@ def filter_recently_fired_workflow_actions( | |
| workflow_ids=workflow_ids, | ||
| ) | ||
| now = timezone.now() | ||
| action_to_workflow_ids, statuses_to_update, missing_statuses = ( | ||
| action_to_workflows_ids, statuses_to_update, missing_statuses = ( | ||
| process_workflow_action_group_statuses( | ||
| action_to_workflows_ids=action_to_workflows_ids, | ||
| action_to_statuses=action_to_statuses, | ||
|
|
@@ -199,14 +222,24 @@ def filter_recently_fired_workflow_actions( | |
| now=now, | ||
| ) | ||
| ) | ||
| update_workflow_action_group_statuses(now, statuses_to_update, missing_statuses) | ||
| _, _, conflicted_statuses = update_workflow_action_group_statuses( | ||
| now, statuses_to_update, missing_statuses | ||
| ) | ||
|
|
||
| # if statuses were not created for some reason, we should not fire for them | ||
| for workflow_id, action_id in conflicted_statuses: | ||
| action_to_workflows_ids[action_id].remove(workflow_id) | ||
| if not action_to_workflows_ids[action_id]: | ||
| action_to_workflows_ids.pop(action_id) | ||
|
|
||
| actions_queryset = Action.objects.filter(id__in=list(action_to_workflow_ids.keys())) | ||
| actions_queryset = Action.objects.filter(id__in=list(action_to_workflows_ids.keys())) | ||
|
|
||
| # annotate actions with workflow_id they are firing for (deduped) | ||
| workflow_id_cases = [ | ||
| When(id=action_id, then=Value(workflow_id)) | ||
| for action_id, workflow_id in action_to_workflow_ids.items() | ||
| When( | ||
| id=action_id, then=Value(min(list(workflow_ids))) | ||
| ) # select 1 workflow to fire for, this is arbitrary but deterministic | ||
| for action_id, workflow_ids in action_to_workflows_ids.items() | ||
| ] | ||
|
|
||
| return actions_queryset.annotate( | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unfortunately the best way to find the rows that were not created was to use a SQL query. Django's
bulk_createdoesn't have a nice way to only populate PKs in the return list for successful creates that didn't conflict