-
Notifications
You must be signed in to change notification settings - Fork 556
feat(cohorts): apply membership deltas to edge identities in batches #8213
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
+1,113
−10
Merged
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
3f1cf1f
feat(cohorts): add cohorts app with membership ledger models
gagantrivedi 60bfba4
feat(identities): add system_traits to engine identity document model
gagantrivedi 4a55cee
fix(identities): exclude system_traits from SDK environment document
gagantrivedi 3d1fbef
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] ce7b24e
chore: merge system_traits branch into applier branch
gagantrivedi 4ebaaa0
feat(cohorts): apply membership deltas to edge identities in batches
gagantrivedi 5fa8c99
fix(cohorts): enforce one active cohort per segment
gagantrivedi 6c502b9
Merge branch 'feat/cohort-sync' into feat/cohort-membership-applier
gagantrivedi 2a36df6
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 1d09e0a
test(cohorts): pin partial unique condition via direct deleted_at update
gagantrivedi 35bfec4
Merge branch 'feat/cohort-sync' into feat/cohort-membership-applier
gagantrivedi 75b4d38
Merge remote-tracking branch 'origin/feat/cohort-membership-applier' …
gagantrivedi 96679df
Merge remote-tracking branch 'origin/main' into feat/cohort-membershi…
gagantrivedi ed368a6
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 679cf05
test(cohorts): cover drained-ledger exit and unexpected ClientError r…
gagantrivedi 676ad18
Merge remote-tracking branch 'origin/feat/cohort-membership-applier' …
gagantrivedi b8c1da6
refactor(cohorts): address review findings on membership applier
gagantrivedi cec54a6
feat(identities): accept trait_value in set_system_trait
gagantrivedi d9ec0e9
refactor(identities): initialise system_traits map via if_not_exists
gagantrivedi 8afeb49
docs(identities): reword conditional-write comments in plain language
gagantrivedi 87db885
docs(identities): say system_traits instead of map in tests and comments
gagantrivedi 4d994a6
refactor(cohorts): move identifier byte-length enforcement to ingestion
gagantrivedi 931e8d5
refactor(cohorts): simplify applier to claim-time state and batches o…
gagantrivedi ecd836d
refactor(identities): confirm system_traits init from returned attrib…
gagantrivedi 77dd067
fix(identities): drop private pydantic IncEx import
gagantrivedi 62c2b9d
Merge remote-tracking branch 'origin/feat/identity-system-traits' int…
gagantrivedi d03e36c
Merge branch 'feat/identity-system-traits' into feat/cohort-membershi…
gagantrivedi 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 |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| COHORT_SYSTEM_TRAIT_KEY_PREFIX = "flagsmith_cohort_" | ||
| COHORT_MEMBERSHIP_APPLY_BATCH_SIZE = 100 | ||
| COHORT_MEMBERSHIP_APPLY_MAX_BATCHES_PER_RUN = 10 | ||
| DYNAMODB_THROTTLING_ERROR_CODES = frozenset( | ||
| { | ||
| "ProvisionedThroughputExceededException", | ||
| "RequestLimitExceeded", | ||
| "ThrottlingException", | ||
| } | ||
| ) |
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 |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| import prometheus_client | ||
|
|
||
| flagsmith_cohorts_membership_deltas_applied_total = prometheus_client.Counter( | ||
| "flagsmith_cohorts_membership_deltas_applied_total", | ||
| "Total number of cohort membership ledger rows transitioned to their " | ||
| "applied state after the corresponding identity document write. " | ||
| "The `operation` label is either `add` or `remove`.", | ||
| ["operation"], | ||
| ) |
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
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 |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import structlog | ||
| from django.db.models import QuerySet | ||
| from django.utils import timezone | ||
|
|
||
| from cohorts.constants import COHORT_MEMBERSHIP_APPLY_BATCH_SIZE | ||
| from cohorts.metrics import flagsmith_cohorts_membership_deltas_applied_total | ||
| from cohorts.models import Cohort, CohortMembership, CohortMembershipState | ||
| from environments.dynamodb import DynamoIdentityWrapper | ||
|
|
||
| logger = structlog.get_logger("cohorts") | ||
|
|
||
| _PENDING_STATES = [ | ||
| CohortMembershipState.PENDING_ADD, | ||
| CohortMembershipState.PENDING_REMOVE, | ||
| ] | ||
|
|
||
|
|
||
| def pending_memberships(cohort: Cohort) -> "QuerySet[CohortMembership]": | ||
| return CohortMembership.objects.filter(cohort=cohort, state__in=_PENDING_STATES) | ||
|
|
||
|
|
||
| def apply_pending_memberships(cohort: Cohort) -> bool: | ||
| identity_wrapper = DynamoIdentityWrapper() | ||
| environment_api_key: str = cohort.environment.api_key | ||
| trait_key = cohort.system_trait_key | ||
| batch = list( | ||
| pending_memberships(cohort).order_by("id")[:COHORT_MEMBERSHIP_APPLY_BATCH_SIZE] | ||
| ) | ||
| if not batch: | ||
| return False | ||
| added_ids: list[int] = [] | ||
| removed_ids: list[int] = [] | ||
| for row in batch: | ||
| if row.state == CohortMembershipState.PENDING_ADD: | ||
| identity_wrapper.set_system_trait( | ||
| environment_api_key=environment_api_key, | ||
| identifier=row.identifier, | ||
| trait_key=trait_key, | ||
| ) | ||
| added_ids.append(row.id) | ||
| else: | ||
| identity_wrapper.unset_system_trait( | ||
| environment_api_key=environment_api_key, | ||
| identifier=row.identifier, | ||
| trait_key=trait_key, | ||
| ) | ||
| removed_ids.append(row.id) | ||
| added_count = CohortMembership.objects.filter( | ||
| id__in=added_ids, state=CohortMembershipState.PENDING_ADD | ||
| ).update(state=CohortMembershipState.APPLIED, updated_at=timezone.now()) | ||
| removed_count, _ = CohortMembership.objects.filter( | ||
| id__in=removed_ids, state=CohortMembershipState.PENDING_REMOVE | ||
| ).delete() | ||
| flagsmith_cohorts_membership_deltas_applied_total.labels(operation="add").inc( | ||
| added_count | ||
| ) | ||
| flagsmith_cohorts_membership_deltas_applied_total.labels(operation="remove").inc( | ||
| removed_count | ||
| ) | ||
| if added_count or removed_count: | ||
| logger.info( | ||
| "membership.applied", | ||
| cohort__id=cohort.id, | ||
| environment__id=cohort.environment_id, | ||
| adds__count=added_count, | ||
| removes__count=removed_count, | ||
| ) | ||
| return pending_memberships(cohort).exists() |
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 |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| from datetime import timedelta | ||
|
|
||
| import structlog | ||
| from botocore.exceptions import ClientError | ||
| from task_processor.decorators import register_task_handler | ||
| from task_processor.exceptions import TaskBackoffError | ||
|
|
||
| from cohorts import services | ||
| from cohorts.constants import ( | ||
| COHORT_MEMBERSHIP_APPLY_MAX_BATCHES_PER_RUN, | ||
| DYNAMODB_THROTTLING_ERROR_CODES, | ||
| ) | ||
| from cohorts.models import Cohort | ||
| from environments.dynamodb import DynamoIdentityWrapper | ||
|
|
||
| logger = structlog.get_logger("cohorts") | ||
|
|
||
|
|
||
| @register_task_handler(timeout=timedelta(minutes=5)) | ||
| def apply_cohort_membership_deltas(cohort_id: int) -> None: | ||
| log = logger.bind(cohort__id=cohort_id) | ||
| if (cohort := Cohort.objects.filter(id=cohort_id).first()) is None: | ||
| log.info("membership.apply.skipped", reason="cohort_missing") | ||
| return | ||
| if not ( | ||
| cohort.environment.project.enable_dynamo_db | ||
| and DynamoIdentityWrapper().is_enabled | ||
| ): | ||
| log.info("membership.apply.skipped", reason="not_edge") | ||
| return | ||
| try: | ||
| for _ in range(COHORT_MEMBERSHIP_APPLY_MAX_BATCHES_PER_RUN): | ||
| if not services.apply_pending_memberships(cohort): | ||
| return | ||
| except ClientError as exc: | ||
| if exc.response["Error"]["Code"] in DYNAMODB_THROTTLING_ERROR_CODES: | ||
| log.warning("membership.apply.throttled") | ||
| raise TaskBackoffError() from exc | ||
| raise | ||
| # Still pending after this run's batch cap; continue in a fresh task run. | ||
| apply_cohort_membership_deltas.delay(kwargs={"cohort_id": cohort_id}) |
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
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
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
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 |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import pytest | ||
|
|
||
| from cohorts.models import Cohort | ||
| from environments.models import Environment | ||
| from projects.models import Project | ||
| from segments.models import Segment | ||
|
|
||
|
|
||
| @pytest.fixture() | ||
| def cohort(environment: Environment, segment: Segment) -> Cohort: | ||
| cohort: Cohort = Cohort.objects.create(environment=environment, segment=segment) | ||
| return cohort | ||
|
|
||
|
|
||
| @pytest.fixture() | ||
| def edge_cohort( | ||
| dynamo_enabled_project: Project, | ||
| dynamo_enabled_project_environment_one: Environment, | ||
| ) -> Cohort: | ||
| segment = Segment.objects.create( | ||
| name="edge segment", project=dynamo_enabled_project | ||
| ) | ||
| cohort: Cohort = Cohort.objects.create( | ||
| environment=dynamo_enabled_project_environment_one, segment=segment | ||
| ) | ||
| return cohort |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.