Build a feature lifecycle service: proposal, RFC, rollout phases, and cleanup.
- User
Build a feature lifecycle service: proposal, RFC, rollout phases, and cleanup.
- Assistant
We are going to design a Feature Lifecycle Service that manages features from proposal to cleanup. The main stages: Proposal, RFC (Request for Comments), Rollout Phases, Cleanup.
We'll have a Feature model and a service that can:
- Propose a new feature (create a feature in proposal state)
- Move feature to RFC state (with RFC document)
- Start rollout phases (can have multiple phases, each with a target audience and rollout plan)
- Complete rollout (mark feature as rolled out)
- Cleanup (archive and eventually delete feature related data)
We'll design the Feature model with state transitions and necessary fields.
Let's assume we have the following states (in order): PROPOSAL -> RFC -> ROLLOUT -> COMPLETED -> CLEANUP
However, note that cleanup is a separate phase that might happen after a feature is completed and after some time.
Alternatively, we can think of lifecycle as: Proposal (idea) -> RFC (design and discussion) -> Rollout (staged rollout to users) -> Completed (fully rolled out) -> Cleanup (after some time, remove old feature flags, config, etc.)
But note: sometimes features might be rejected or abandoned. So we might also have a REJECTED state.
Let's define states: PROPOSAL, RFC, ROLLOUT, COMPLETED, CLEANUP, REJECTED, ARCHIVED
Transitions: PROPOSAL -> RFC (when we decide to write an RFC) PROPOSAL -> REJECTED (if rejected early) RFC -> ROLLOUT (when RFC is approved and we start rollout) RFC -> REJECTED (if rejected after RFC) ROLLOUT -> COMPLETED (when rollout is 100% and stable) ROLLOUT -> REJECTED (if we decide to roll back and abandon) COMPLETED -> CLEANUP (after some time, we start cleanup) CLEANUP -> ARCHIVED (when cleanup is done)
We might also have a ROLLBACK transition from ROLLOUT to PROPOSAL? But typically if we rollback we might reject.
However, note that the cleanup phase might be a separate process that runs periodically on completed features that are old enough.
Let's design the Feature model:
id: primary key name: string description: text state: enum (PROPOSAL, RFC, ROLLOUT, COMPLETED, CLEANUP, REJECTED, ARCHIVED) created_at: datetime updated_at: datetime
RFC specific: rfc_document_url: string (nullable, required when state is RFC or beyond, but not for PROPOSAL)
Rollout specific: rollout_plan: JSON field? or we can have a separate RolloutPhase model.
We can have a separate model for RolloutPhase to support multiple phases.
Let's create a RolloutPhase model:
id: primary key feature_id: foreign key to Feature phase_number: integer (1,2,3...) target_percentage: integer (0-100) target_audience: string (could be a segment name or description) start_date: date end_date: date (nullable, if not set then ongoing until next phase or completion) status: enum (PLANNED, IN_PROGRESS, COMPLETED, CANCELLED)But note: we might not need a separate model if we just want to track the current phase and overall rollout progress.
Alternatively, we can have in Feature: current_rollout_phase: integer rollout_percentage: integer (0-100) - current overall rollout percentage.
However, having a separate model for phases gives us history and more control.
Let's go with separate RolloutPhase model.
Then in Feature, we can have: current_phase: integer (the current phase number, 0 if not started)
But we can also compute current phase from RolloutPhase model (the latest phase that is IN_PROGRESS or the last COMPLETED if none in progress).
Alternatively, we can avoid current_phase in Feature and just query RolloutPhase.
However, for quick access, we might want to store the current phase in Feature.
Let's keep it simple: we store current_phase in Feature, and RolloutPhase model has the history and plan.
Also, we need to track the overall rollout status? We can compute from RolloutPhases.
But note: we might want to have a field for overall rollout percentage that is updated as we go.
Alternatively, we can have:
Feature: ... rollout_status: enum (NOT_STARTED, IN_PROGRESS, COMPLETED) - but this can be derived.Let's derive from RolloutPhases and current_phase.
Steps:
When we start rollout (state becomes ROLLOUT), we create a RolloutPhase with phase_number=1, and set Feature.current_phase=1.
When we move to next phase, we mark the current phase as COMPLETED and create a new RolloutPhase with next phase_number, and update Feature.current_phase.
When the last phase is completed (or we reach 100% and no more phases), we set Feature.state to COMPLETED.
But note: we might have multiple phases and then complete at 100% in the middle of a phase? Then we complete the current phase and then complete the feature.
Alternatively, we can have a phase that goes until 100% and then we complete the feature.
Let's design:
RolloutPhase: target_percentage: the target percentage for this phase (must be increasing? we can validate that in the service) We can have a phase that covers 0-50%, then 50-80%, then 80-100%. Then when we reach 100% in a phase, we complete that phase and then complete the feature.But note: we might have a phase that is 100% and then we complete the feature.
Alternatively, we can have a phase that is "until 100%" and then we complete.
Let's not overcomplicate: we have phases with target_percentage, and when we reach that percentage we mark the phase as completed and then either start the next phase or complete the feature.
We'll need a way to update the current rollout percentage. This might come from an external source (like user assignment system).
So we might have in Feature:
current_rollout_percentage: integer (0-100)And then in the service, when we update the percentage, we check if we have completed the current phase and then move to next phase or complete.
But note: the phases are planned, so we might not want to automatically move to next phase? We might want to manually advance.
Let's decide:
We have two ways:
-
Manual: we manually mark a phase as completed and start the next one, and we manually set the rollout percentage.
-
Automatic: when the current_rollout_percentage reaches or exceeds the current phase's target_percentage, we automatically complete the phase and start the next one.
We can support both? Or we can have a flag for automatic progression.
For simplicity, let's do manual progression. The rollout percentage is updated by an external process (like the system that assigns features to users) and we just track it.
Then when we want to move to the next phase, we call the service to advance the phase, which will:
- Check that the current phase's target_percentage has been reached (or we can ignore and just advance?). - Mark current phase as COMPLETED. - If there is a next planned phase, create it and set as IN_PROGRESS, and update Feature.current_phase. - If there is no next phase, then we set Feature.state to COMPLETED.Alternatively, we can have a planned set of phases and when we start rollout we create all phases? Or we create them on the fly.
Let's create phases on the fly when we advance. We can store the plan in the Feature model? Maybe as a JSON array of phases? Or we can have a separate model for RolloutPlan? But we already have RolloutPhase.
Alternatively, we can have:
Feature: ... rollout_phases: JSON field that stores the plan (list of phases with target_percentage and target_audience)Then when we start rollout, we create the first RolloutPhase from the plan.
But then if we want to change the plan, we can update the JSON and then when we advance, we create the next phase from the plan.
However, we might want to keep history of what actually happened. So having RolloutPhase as a separate model that records the actual start/end dates and status is good.
Let's do:
Feature has a JSON field `rollout_plan` which is an array of objects: [ { "phase_number": 1, "target_percentage": 50, "target_audience": "internal" }, { "phase_number": 2, "target_percentage": 80, "target_audience": "beta" }, { "phase_number": 3, "target_percentage": 100, "target_audience": "all" } ] Then when we start rollout, we create RolloutPhase records for each phase in the plan? Or we create the first one and then create the next when we advance? We can create all phases in advance with status PLANNED, and then when we start the first phase, we set it to IN_PROGRESS. Then when we advance, we set the current to COMPLETED and set the next to IN_PROGRESS. This way we have the whole plan recorded. Alternatively, we can create phases only when they start? But then we lose the plan if we don't create them. Let's create all phases at the time of starting rollout, with status PLANNED, and then set the first to IN_PROGRESS. Then when we advance, we complete the current and set the next to IN_PROGRESS. If we want to skip a phase, we can mark the current as COMPLETED and then set a future phase to IN_PROGRESS? But then we break the sequence. We can enforce that we only advance to the next phase in the plan. So: RolloutPhase: id feature_id phase_number (integer, must be unique per feature and sequential) target_percentage target_audience start_date (when the phase started, set when we set status to IN_PROGRESS) end_date (when the phase ended, set when we set status to COMPLETED) status Feature: ... rollout_plan: JSON (the plan, which we use to create the RolloutPhase records) When we start rollout (from RFC state), we: - Validate that rollout_plan is present and has at least one phase. - Create RolloutPhase records for each phase in the plan, with status PLANNED. - Set the first phase (phase_number=1) to IN_PROGRESS, set its start_date to now. - Set Feature.current_phase = 1 - Set Feature.state = ROLLOUT When we advance to next phase (via service call), we: - Check that the current phase (Feature.current_phase) is COMPLETED? Or we complete it as part of the advance? - We can have two actions: complete current phase and then start next. Let's create an action `advance_rollout_phase` that: 1. Marks the current phase (current_phase) as COMPLETED, sets end_date to now. 2. Increments current_phase by 1. 3. Finds the RolloutPhase with the new current_phase and sets it to IN_PROGRESS, sets start_date to now. 4. If there is no next phase (i.e., we just completed the last phase), then set Feature.state to COMPLETED and current_phase to null? Or leave it as the last phase number? But note: when we complete the last phase, we set the feature to COMPLETED and then we don't have a current phase. Alternatively, we can set current_phase to null when completed. But then when we look at the RolloutPhase, the last one is COMPLETED. So: When we start rollout: current_phase = 1, state = ROLLOUT. When we advance and there is a next phase: current_phase = 2, state = ROLLOUT. When we advance and there is no next phase: current_phase = null, state = COMPLETED. Also, we must ensure that the current_rollout_percentage (in Feature) has reached the target_percentage of the current phase? We can check that as a condition for advancing. So in `advance_rollout_phase`: current_phase_rollout = Feature.current_rollout_percentage current_phase_target = RolloutPhase.objects.get(feature=feature, phase_number=feature.current_phase).target_percentage if current_phase_rollout < current_phase_target: raise error("Cannot advance: current phase target not reached") But note: we might want to allow manual override? Then we can have a flag `force` that skips the check. For now, we require the target to be reached.Now, cleanup:
We might have a scheduled job that runs periodically and moves features from COMPLETED to CLEANUP if they are old enough (e.g., completed for 30 days). Then we have a cleanup process that does the necessary cleanup (delete feature flags, remove config, etc.) and then marks the feature as ARCHIVED. We can have a service method `start_cleanup` that: - Checks that the feature is in COMPLETED state and completed for at least X days (configurable?). - Sets the feature state to CLEANUP. - Then we run the cleanup tasks (which might be external, so we just trigger an event or call a hook). - After cleanup is done, we mark the feature as ARCHIVED. Alternatively, we can have two steps: 1. Mark for cleanup (state becomes CLEANUP) and then a background job runs the cleanup. 2. After cleanup, the background job sets state to ARCHIVED. But note: the cleanup might fail, so we need to handle that. We can have a Cleanup model that tracks cleanup attempts and status? Or we can just have state transitions. Let's keep it simple: Feature.state goes from COMPLETED -> CLEANUP -> ARCHIVED. We have a service method `start_cleanup` that changes state to CLEANUP and then triggers a cleanup task (maybe a Celery task). The cleanup task does the work and then calls `complete_cleanup` to set state to ARCHIVED. If the cleanup fails, we might retry or leave in CLEANUP state and have an alert. Alternatively, we can have a separate Cleanup model that records: id, feature_id, started_at, completed_at, status, error_message. Then when we start cleanup, we create a Cleanup record with status IN_PROGRESS. Then the cleanup task updates the record and the feature state. But for simplicity, let's just use the Feature state and assume the cleanup task will update the state. However, we might want to track multiple cleanup attempts? Then we need a separate model. Since this is a design, let's go with: Feature.state: CLEANUP means cleanup is in progress. Then when cleanup is done (success or failure), we set to ARCHIVED if success, or maybe back to COMPLETED? But if failure, we might want to retry. Alternatively, we can have: CLEANUP_IN_PROGRESS, CLEANUP_FAILED, ARCHIVED. But then we have more states. Let's stick to: COMPLETED -> CLEANUP (meaning cleanup is triggered) -> ARCHIVED (when done). If cleanup fails, we can leave it in CLEANUP and retry, or set to CLEANUP_FAILED and then manually intervene. For now, we'll assume cleanup always succeeds and we just set to ARCHIVED. But in reality, we might have: CLEANUP_IN_PROGRESS, CLEANUP_SUCCEEDED, CLEANUP_FAILED. Then we can have: COMPLETED -> CLEANUP_IN_PROGRESS -> CLEANUP_SUCCEEDED -> ARCHIVED. Or if failed: CLEANUP_IN_PROGRESS -> CLEANUP_FAILED -> (retry? then back to CLEANUP_IN_PROGRESS) or manual intervention. This is getting complex. Since the requirement is just to have a cleanup phase, let's keep it simple and assume: We have a state CLEANUP that means we are cleaning up, and then we set to ARCHIVED when done. We can have a boolean `cleanup_failed`? Or just use state CLEANUP for in progress and ARCHIVED for done. But what about failure? We might want to retry. Alternatively, we can have: states: PROPOSAL, RFC, ROLLOUT, COMPLETED, CLEANUP, ARCHIVED, REJECTED. And we can have a field `cleanup_attempts` and `last_cleanup_error` to track. But again, let's not overengineer. Given the time, we'll do: When we start cleanup, we set state to CLEANUP. Then we run the cleanup (synchronously or asynchronously). If it succeeds, set state to ARCHIVED. If it fails, we set state to CLEANUP_FAILED? But we don't have that state. So let's add CLEANUP_FAILED. Now states: PROPOSAL, RFC, ROLLOUT, COMPLETED, CLEANUP, CLEANUP_FAILED, ARCHIVED, REJECTED. Transitions: COMPLETED -> CLEANUP (start cleanup) CLEANUP -> ARCHIVED (success) CLEANUP -> CLEANUP_FAILED (failure) Then we can have a way to retry from CLEANUP_FAILED to CLEANUP. But note: we might want to automatically retry? Then we can have a scheduled job that retries failed cleanups. Alternatively, we can have: COMPLETED -> CLEANUP (start cleanup) CLEANUP -> ARCHIVED (success) CLEANUP -> CLEANUP_FAILED (failure) And then from CLEANUP_FAILED we can manually or automatically retry by going back to CLEANUP. We'll leave that for now.Now, let's write the code structure:
We'll have: models.py: class Feature(models.Model): STATE_CHOICES = [ ('PROPOSAL', 'Proposal'), ('RFC', 'RFC'), ('ROLLOUT', 'Rollout'), ('COMPLETED', 'Completed'), ('CLEANUP', 'Cleanup'), ('CLEANUP_FAILED', 'Cleanup Failed'), ('ARCHIVED', 'Archived'), ('REJECTED', 'Rejected'), ] name = models.CharField(max_length=255) description = models.TextField() state = models.CharField(max_length=20, choices=STATE_CHOICES, default='PROPOSAL') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # RFC rfc_document_url = models.URLField(blank=True, null=True) # Rollout rollout_plan = models.JSONField(default=list) # list of phase objects current_phase = models.IntegerField(null=True, blank=True) # the current phase number, null if not in rollout or completed current_rollout_percentage = models.IntegerField(default=0) # 0-100 # Cleanup cleanup_attempts = models.IntegerField(default=0) last_cleanup_error = models.TextField(blank=True, null=True) def __str__(self): return self.name class RolloutPhase(models.Model): feature = models.ForeignKey(Feature, on_delete=models.CASCADE, related_name='rollout_phases') phase_number = models.IntegerField() target_percentage = models.IntegerField() target_audience = models.CharField(max_length=255) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) status = models.CharField( max_length=20, choices=[ ('PLANNED', 'Planned'), ('IN_PROGRESS', 'In Progress'), ('COMPLETED', 'Completed'), ('CANCELLED', 'Cancelled') ], default='PLANNED' ) class Meta: unique_together = ('feature', 'phase_number') ordering = ['phase_number'] def __str__(self): return f"{self.feature.name} - Phase {self.phase_number}" Then we have a service layer that handles state transitions and business logic. We'll create a FeatureLifecycleService with methods: propose_feature(name, description) -> Feature submit_rfc(feature_id, rfc_document_url) -> Feature start_rollout(feature_id) -> Feature advance_rollout_phase(feature_id, force=False) -> Feature complete_rollout(feature_id) -> Feature # maybe we don't need this if we complete when last phase is done? reject_feature(feature_id, reason) -> Feature start_cleanup(feature_id) -> Feature complete_cleanup(feature_id) -> Feature # called by cleanup task on success fail_cleanup(feature_id, error_message) -> Feature # called by cleanup task on failure But note: we might not have a complete_rollout method because we complete when the last phase is advanced. However, we might want to complete without advancing to the next phase? For example, if we have 3 phases and we are at phase 2 and we decide to complete early? Then we can have a method to complete the rollout. Alternatively, we can have: complete_rollout(feature_id) -> Feature that sets the state to COMPLETED and marks all remaining phases as CANCELLED? Or just sets the state and we leave the phases as they are? But note: if we complete early, we might not have done all phases. So we can have: complete_rollout(feature_id) that: - Sets Feature.state = COMPLETED. - Sets current_phase to null. - Marks the current phase (if any) as COMPLETED? And then cancels the rest? Alternatively, we can just set the state and leave the phases as is? But then we have a phase that is IN_PROGRESS and the feature is completed? That's inconsistent. So when we complete the rollout (either by advancing through all phases or by early completion), we should: - Set state to COMPLETED. - Set current_phase to null. - Mark the current phase (the one that was in progress) as COMPLETED. - Mark all future phases (with phase_number > current_phase) as CANCELLED. Then, if we complete by advancing through all phases, we already mark the last phase as COMPLETED and then set state to COMPLETED. So we can have: In `advance_rollout_phase`, when we advance and there is no next phase, we set state to COMPLETED and set current_phase to null, and mark the last phase as COMPLETED. In `complete_rollout` (for early completion), we do: current_phase = feature.current_phase if current_phase is not None: current_phase_obj = RolloutPhase.objects.get(feature=feature, phase_number=current_phase) current_phase_obj.status = 'COMPLETED' current_phase_obj.end_date = timezone.now() current_phase_obj.save() # Cancel all phases with phase_number > current_phase RolloutPhase.objects.filter(feature=feature, phase_number__gt=current_phase).update(status='CANCELLED') feature.state = 'COMPLETED' feature.current_phase = None feature.save() Now, what about the rollout percentage? When we complete early, we might not have reached 100%? But we are completing, so we should set the current_rollout_percentage to 100%? Or leave it as is? Since we are completing, we can set it to 100% to indicate it's fully rolled out. So in `complete_rollout`: feature.current_rollout_percentage = 100 But note: if we complete early, we might have only rolled out to 50%? Then we are completing for 50%? That doesn't make sense. Actually, if we complete the rollout, it means we are done and the feature is available to all? Then we should set to 100%. So we set to 100%. Similarly, when we advance through phases, we update the current_rollout_percentage to the current phase's target_percentage? Or we let the external system update it? We might want to update the current_rollout_percentage when we advance? Because if we advance, we have reached the target of the current phase, so we set the current_rollout_percentage to at least that target. But note: the external system might set it to more than the target? Then we set it to the current_rollout_percentage. Actually, the current_rollout_percentage is the actual rollout percentage, which is updated by the external system. So when we advance, we don't change the current_rollout_percentage, we just check that it has reached the target. So: In `advance_rollout_phase`: current_phase = feature.current_phase if current_phase is None: raise error("No current phase") current_phase_obj = RolloutPhase.objects.get(feature=feature, phase_number=current_phase) if feature.current_rollout_percentage < current_phase_obj.target_percentage: raise error("Current rollout percentage is less than the target of the current phase") # Then mark current_phase_obj as COMPLETED, set end_date. # Then find the next phase (phase_number = current_phase+1) that is PLANNED. # If found, set it to IN_PROGRESS, set start_date, and update feature.current_phase = current_phase+1. # If not found, then set feature.state = COMPLETED, feature.current_phase = None, and set feature.current_rollout_percentage = 100 (if not already 100? But we know the last phase target is 100, so it should be 100). But wait: the last phase's target might be 100, but what if we have a phase that is 100 and then we complete? Then we set to 100 again. So it's safe. Now, what about cleanup: We have a scheduled job that runs every day and for every feature in COMPLETED state that was completed at least 30 days ago, we call `start_cleanup`. Then `start_cleanup`: - Checks that state is COMPLETED and completed_at (we don't have a completed_at field) is at least 30 days ago. We don't have a completed_at field. We can use the updated_at when the state changed to COMPLETED? But updated_at changes on every save. We can add a `completed_at` field that is set when we set state to COMPLETED. So in Feature model: completed_at = models.DateTimeField(null=True, blank=True) Then when we set state to COMPLETED, we set completed_at = timezone.now(). Then in the cleanup job, we check: completed_at <= timezone.now() - timedelta(days=30) Then we call `start_cleanup`. `start_cleanup`: - Sets state to CLEANUP. - Increments cleanup_attempts. - Then triggers the cleanup task (asynchronously). The cleanup task does the actual cleanup (deleting feature flags, etc.) and then: On success: calls `complete_cleanup`. On failure: calls `fail_cleanup`. `complete_cleanup`: - Sets state to ARCHIVED. `fail_cleanup`: - Sets state to CLEANUP_FAILED. - Sets last_cleanup_error. Then we can have a retry mechanism for CLEANUP_FAILED.This is a basic design.
Let's code the service methods with state transition checks.
We'll use Django and create a service class.
We'll also have to handle invalid transitions.
We'll define a state machine.
Allowed transitions:
PROPOSAL -> RFC PROPOSAL -> REJECTED RFC -> ROLLOUT RFC -> REJECTED ROLLOUT -> COMPLETED (via advance_rollout_phase when no next phase, or via complete_rollout) ROLLOUT -> REJECTED (if we want to abandon during rollout) COMPLETED -> CLEANUP CLEANUP -> ARCHIVED CLEANUP -> CLEANUP_FAILED CLEANUP_FAILED -> CLEANUP (for retry) Also, from any state we might want to REJECT? But typically we can reject from PROPOSAL, RFC, ROLLOUT. So: From PROPOSAL, RFC, ROLLOUT -> REJECTED. And from REJECTED we can go to ARCHIVED? Or we archive rejected features? We might have a separate archival for rejected. Let's say: REJECTED -> ARCHIVED (after some time? or immediately?) We can have a scheduled job that archives rejected features after 30 days. But we already have a cleanup for completed. We can have a similar for rejected. Alternatively, we can have: REJECTED -> ARCHIVED (immediately? or after a period) For simplicity, we can have a state ARCHIVED that is the final state for both completed and rejected. So we can have: COMPLETED -> CLEANUP -> ARCHIVED REJECTED -> ARCHIVED (maybe after a period, but we can do immediate) But note: we might want to do cleanup for rejected features too? Maybe not, because they were never rolled out. So for rejected, we just archive. Then we can have: reject_feature(feature_id) that sets state to REJECTED. And then a scheduled job that moves REJECTED to ARCHIVED after 30 days? Or we can do it immediately. Let's do: When we reject, we set state to REJECTED. And then we have a job that runs and for any feature in REJECTED that is older than 30 days, set to ARCHIVED. But we don't have a rejected_at field. We can use the updated_at when we set to REJECTED? But updated_at changes on every save. So we add: rejected_at = models.DateTimeField(null=True, blank=True) completed_at = models.DateTimeField(null=True, blank=True) Then when we set state to REJECTED, we set rejected_at = timezone.now(). Similarly for COMPLETED. Then the archival job: For features in REJECTED with rejected_at <= now - 30 days, set state to ARCHIVED. For features in COMPLETED with completed_at <= now - 30 days and state not in [CLEANUP, CLEANUP_FAILED, ARCHIVED]? Actually, we only start cleanup for COMPLETED after 30 days, so if it's in CLEANUP or CLEANUP_FAILED, we are already in the process. But note: we start cleanup for COMPLETED after 30 days, so we don't archive until cleanup is done. So the archival job for completed features should only archive those that are in ARCHIVED state? Wait, we have: COMPLETED -> CLEANUP -> ARCHIVED So the archival job for completed should look for state=ARCHIVED? But we set to ARCHIVED after cleanup. Actually, we want to archive the feature data after cleanup? But the state ARCHIVED means we have archived the feature. So we don't need a separate job for completed to archive? Because we already have the cleanup that leads to ARCHIVED. But what about rejected? We don't have a cleanup for rejected, so we need a job to move REJECTED to ARCHIVED. So: We have two jobs: 1. Cleanup starter: for COMPLETED features with completed_at <= now - 30 days and state still COMPLETED, start cleanup. 2. Archiver: for REJECTED features with rejected_at <= now - 30 days, set state to ARCHIVED. And also for CLEANUP_FAILED? We might want to retry? Or after some time, we might want to archive them? But if cleanup failed, we might not want to archive until we fix. So we don't archive CLEANUP_FAILED automatically. So: Archiver job: - For features in REJECTED and rejected_at <= now - 30 days: set state to ARCHIVED. Cleanup starter job: - For features in COMPLETED and completed_at <= now - 30 days: start_cleanup. And we have a retry for cleanup failures? We can have a separate job that retries CLEANUP_FAILED after some time. But let's keep it simple and not implement retry for now.Now, let's write the service class with all the methods and state transition checks.
We'll use Django signals? Or just call the service methods from views?
We'll create a service class that we can call from views or management commands.
We'll also have to handle invalid state transitions.
Let's define a state machine:
PROPOSAL -> RFC PROPOSAL -> REJECTED RFC -> ROLLOUT RFC -> REJECTED ROLLOUT -> COMPLETED ROLLOUT -> REJECTED COMPLETED -> CLEANUP CLEANUP -> ARCHIVED CLEANUP -> CLEANUP_FAILED CLEANUP_FAILED -> CLEANUP REJECTED -> ARCHIVEDNow, code the service:
class FeatureLifecycleService: def propose_feature(self, name, description): feature = Feature.objects.create( name=name, description=description, state='PROPOSAL' ) return feature def submit_rfc(self, feature_id, rfc_document_url): feature = self._get_feature(feature_id) self._validate_transition(feature, 'PROPOSAL', 'RFC') feature.rfc_document_url = rfc_document_url feature.state = 'RFC' feature.save() return feature def start_rollout(self, feature_id): feature = self._get_feature(feature_id) self._validate_transition(feature, 'RFC', 'ROLLOUT') # Validate rollout_plan is not empty if not feature.rollout_plan: raise ValueError("Rollout plan is required") # Create RolloutPhase records from rollout_plan for phase_data in feature.rollout_plan: phase_number = phase_data['phase_number'] target_percentage = phase_data['target_percentage'] target_audience = phase_data['target_audience'] RolloutPhase.objects.create( feature=feature, phase_number=phase_number, target_percentage=target_percentage, target_audience=target_audience, status='PLANNED' ) # Start the first phase first_phase = feature.rollout_phases.get(phase_number=1) first_phase.status = 'IN_PROGRESS' first_phase.start_date = timezone.now() first_phase.save() feature.current_phase = 1 feature.state = 'ROLLOUT' feature.save() return feature def advance_rollout_phase(self, feature_id, force=False): feature = self._get_feature(feature_id) self._validate_transition(feature, 'ROLLOUT', 'ROLLOUT') # staying in rollout current_phase_num = feature.current_phase if current_phase_num is None: raise ValueError("No current rollout phase") current_phase = feature.rollout_phases.get(phase_number=current_phase_num) if not force and feature.current_rollout_percentage < current_phase.target_percentage: raise ValueError(f"Current rollout percentage {feature.current_rollout_percentage} is less than the target {current_phase.target_percentage}") # Complete the current phase current_phase.status = 'COMPLETED' current_phase.end_date = timezone.now() current_phase.save() # Find the next phase next_phase = feature.rollout_phases.filter(phase_number=current_phase_num+1, status='PLANNED').first() if next_phase: next_phase.status = 'IN_PROGRESS' next_phase.start_date = timezone.now() next_phase.save() feature.current_phase = current_phase_num + 1 else: # No next phase, so complete the rollout feature.state = 'COMPLETED' feature.completed_at = timezone.now() feature.current_phase = None feature.current_rollout_percentage = 100 # ensure 100% feature.save() return feature def complete_rollout(self, feature_id): # This is for early completion, without going through all phases. feature = self._get_feature(feature_id) self._validate_transition(feature, 'ROLLOUT', 'COMPLETED') # If there is a current phase, complete it and cancel the rest. current_phase_num = feature.current_phase if current_phase_num is not None: current_phase = feature.rollout_phases.get(phase_number=current_phase_num) current_phase.status = 'COMPLETED' current_phase.end_date = timezone.now() current_phase.save() # Cancel future phases feature.rollout_phases.filter(phase_number__gt=current_phase_num).update(status='CANCELLED') feature.state = 'COMPLETED' feature.completed_at = timezone.now() feature.current_phase = None feature.current_rollout_percentage = 100 feature.save() return feature def reject_feature(self, feature_id, reason=None): feature = self._get_feature(feature_id) # We can reject from PROPOSAL, RFC, ROLLOUT. if feature.state not in ['PROPOSAL', 'RFC', 'ROLLOUT']: raise ValueError(f"Cannot reject feature in state {feature.state}") feature.state = 'REJECTED' feature.rejected_at = timezone.now() # We might want to store the reason? We don't have a field for that. # We can add a field `rejection_reason` or use a note? For now, we don't store. feature.save() return feature def start_cleanup(self, feature_id): feature = self._get_feature(feature_id) self._validate_transition(feature, 'COMPLETED', 'CLEANUP') feature.state = 'CLEANUP' feature.cleanup_attempts += 1 feature.save() # Trigger async cleanup task (we assume there is a task `cleanup_feature` that does the work) from .tasks import cleanup_feature cleanup_feature.delay(feature_id) return feature def complete_cleanup(self, feature_id): feature = self._get_feature(feature_id) self._validate_transition(feature, 'CLEANUP', 'ARCHIVED') feature.state = 'ARCHIVED' feature.save() return feature def fail_cleanup(self, feature_id, error_message): feature = self._get_feature(feature_id) self._validate_transition(feature, 'CLEANUP', 'CLEANUP_FAILED') feature.state = 'CLEANUP_FAILED' feature.last_cleanup_error = error_message feature.save() return feature def _get_feature(self, feature_id): try: return Feature.objects.get(id=feature_id) except Feature.DoesNotExist: raise ValueError("Feature not found") def _validate_transition(self, feature, from_state, to_state): if feature.state != from_state: raise ValueError(f"Invalid transition: cannot change from {feature.state} to {to_state}") Then we have a scheduled job (management command) that runs the cleanup starter and archiver. But note: we might want to move rejected features to archived after 30 days. We can have: def archive_old_features(): # Archive rejected features older than 30 days cutoff = timezone.now() - timedelta(days=30) Feature.objects.filter(state='REJECTED', rejected_at__lte=cutoff).update(state='ARCHIVED') And the cleanup starter: def start_cleanup_for_old_completed(): cutoff = timezone.now() - timedelta(days=30) features = Feature.objects.filter(state='COMPLETED', completed_at__lte=cutoff) for feature in features: try: service.start_cleanup(feature.id) except Exception as e: # log error and continue logger.error(f"Failed to start cleanup for feature {feature.id}: {e}") We run these periodically.This is a basic structure.
We might need to handle more edge cases, but this should cover the main flow.
Let me know if you have any questions or need more details. I'll design a comprehensive Feature Lifecycle Service that manages features from proposal to cleanup. This service will handle state transitions, approvals, phased rollouts, and eventual decommissioning.
Architecture Overview
graph TD A[Proposal] --> B[RFC] B --> C[Rollout Phases] C --> D[Fully Rolled Out] D --> E[Completed] E --> F[Cleanup] F --> G[Archived] B --> H[Rejected] C --> H D --> HCore Models
# models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator, MaxValueValidator class Feature(models.Model): """Main feature entity tracking lifecycle""" LIFE_CYCLE_STATES = [ ('PROPOSAL', 'Proposal'), ('RFC', 'RFC Review'), ('ROLLOUT', 'Rollout in Progress'), ('COMPLETED', 'Fully Rolled Out'), ('COMPLETED_CLEANUP_PENDING', 'Completed - Cleanup Pending'), ('ARCHIVED', 'Archived'), ('REJECTED', 'Rejected'), ('CANCELLED', 'Cancelled'), ] ROLLOUT_PHASES = [ ('INTERNAL', 'Internal Testing'), ('BETA', 'Beta Release'), ('GA', 'General Availability'), ('ENFORCEMENT', 'Enforcement Phase'), ] name = models.CharField(max_length=200, unique=True) description = models.TextField() state = models.CharField( max_length=40, choices=LIFE_CYCLE_STATES, default='PROPOSAL' ) owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='owned_features') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # RFC Fields rfc_url = models.URLField(blank=True, null=True) rfc_approvers = models.ManyToManyField(User, blank=True, related_name='rfc_approvals') rfc_approval_date = models.DateTimeField(blank=True, null=True) rfc_decision = models.CharField( max_length=20, choices=[('APPROVED', 'Approved'), ('REJECTED', 'Rejected'), ('NEEDS_REVISION', 'Needs Revision')], blank=True, null=True ) # Rollout Fields rollout_phase = models.CharField( max_length=20, choices=ROLLOUT_PHASES, blank=True, null=True ) rollout_start_date = models.DateTimeField(blank=True, null=True) rollout_completion_date = models.DateTimeField(blank=True, null=True) rollout_percentage = models.IntegerField( default=0, validators=[MinValueValidator(0), MaxValueValidator(100)] ) target_rollout_date = models.DateField(blank=True, null=True) # Cleanup Fields cleanup_scheduled_date = models.DateField(blank=True, null=True) cleanup_completed_date = models.DateTimeField(blank=True, null=True) cleanup_notes = models.TextField(blank=True, null=True) class Meta: ordering = ['-created_at'] def __str__(self): return f"{self.name} ({self.state})" class FeaturePhase(models.Model): """Individual rollout phases with metrics""" feature = models.ForeignKey(Feature, on_delete=models.CASCADE, related_name='phases') phase_name = models.CharField(max_length=50) description = models.TextField() target_audience = models.CharField(max_length=200) start_date = models.DateTimeField() end_date = models.DateTimeField(blank=True, null=True) target_percentage = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(100)] ) actual_percentage = models.IntegerField(default=0) success_metrics = models.JSONField(default=dict) issues = models.JSONField(default=list, blank=True) is_completed = models.BooleanField(default=False) class Meta: ordering = ['start_date'] unique_together = ['feature', 'phase_name'] def __str__(self): return f"{self.feature.name} - {self.phase_name}" class FeatureComment(models.Model): """Discussion and decision tracking""" feature = models.ForeignKey(Feature, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.PROTECT) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) is_decision = models.BooleanField(default=False) decision_type = models.CharField( max_length=50, choices=[ ('APPROVAL', 'Approval'), ('REJECTION', 'Rejection'), ('REQUEST_CHANGE', 'Request for Changes'), ('OTHER', 'Other Decision') ], blank=True, null=True ) class Meta: ordering = ['created_at'] class FeatureDependency(models.Model): """Track dependencies between features""" primary_feature = models.ForeignKey( Feature, on_delete=models.CASCADE, related_name='dependencies' ) dependent_feature = models.ForeignKey( Feature, on_delete=models.CASCADE, related_name='dependents' ) dependency_type = models.CharField( max_length=50, choices=[ ('BLOCKING', 'Blocking'), ('SOFT_DEPENDENCY', 'Soft Dependency'), ('TECHNICAL', 'Technical Dependency') ] ) description = models.TextField(blank=True, null=True) class Meta: unique_together = ['primary_feature', 'dependent_feature', 'dependency_type'] class CleanupTask(models.Model): """Track cleanup tasks and their execution""" feature = models.OneToOneField( Feature, on_delete=models.CASCADE, related_name='cleanup_task' ) tasks = models.JSONField(default=list) # List of cleanup tasks assigned_to = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True, related_name='cleanup_tasks' ) due_date = models.DateField() completed_date = models.DateTimeField(blank=True, null=True) status = models.CharField( max_length=20, choices=[ ('PENDING', 'Pending'), ('IN_PROGRESS', 'In Progress'), ('COMPLETED', 'Completed'), ('BLOCKED', 'Blocked') ], default='PENDING' ) notes = models.TextField(blank=True, null=True)State Machine & Transitions
# services/feature_service.py from django.core.exceptions import ValidationError from django.utils import timezone from .models import Feature class FeatureLifecycleService: """Manages feature state transitions and lifecycle operations""" # Valid state transitions matrix VALID_TRANSITIONS = { 'PROPOSAL': ['RFC', 'REJECTED', 'CANCELLED'], 'RFC': ['ROLLOUT', 'REJECTED', 'CANCELLED'], 'ROLLOUT': ['COMPLETED', 'CANCELLED'], 'COMPLETED': ['COMPLETED_CLEANUP_PENDING'], 'COMPLETED_CLEANUP_PENDING': ['ARCHIVED'], } @staticmethod def validate_transition(feature, new_state): """Validate if state transition is allowed""" if new_state not in Feature.VALID_TRANSITIONS.get(feature.state, []): raise ValidationError( f"Cannot transition from {feature.state} to {new_state}" ) @staticmethod def transition_feature(feature, new_state, user=None, **kwargs): """Perform state transition with validation and side effects""" FeatureLifecycleService.validate_transition(feature, new_state) old_state = feature.state feature.state = new_state feature.updated_at = timezone.now() # Set timestamps based on transition if new_state == 'RFC' and not feature.rfc_url: raise ValidationError("RFC URL is required for RFC state") if new_state == 'ROLLOUT': feature.rollout_start_date = timezone.now() if not feature.phases.exists(): # Auto-create default phases if none exist FeatureLifecycleService._create_default_phases(feature) if new_state == 'COMPLETED': feature.rollout_completion_date = timezone.now() # Schedule cleanup 90 days after completion feature.cleanup_scheduled_date = timezone.now().date() + timezone.timedelta(days=90) if new_state == 'COMPLETED_CLEANUP_PENDING': feature.cleanup_scheduled_date = kwargs.get('cleanup_date', timezone.now().date()) if new_state == 'ARCHIVED': feature.cleanup_completed_date = timezone.now() # Record who made the change if user: FeatureComment.objects.create( feature=feature, author=user, content=f"State changed from {old_state} to {new_state}", is_decision=True, decision_type='OTHER' ) feature.save() return feature @staticmethod def _create_default_phases(feature): """Create default rollout phases if none exist""" default_phases = [ { 'phase_name': 'Internal Testing', 'description': 'Test with internal team', 'target_audience': 'Engineering & Product', 'target_percentage': 10, }, { 'phase_name': 'Closed Beta', 'description': 'Limited beta with select customers', 'target_audience': 'Beta Customers', 'target_percentage': 25, }, { 'phase_name': 'Open Beta', 'description': 'Open to all interested users', 'target_audience': 'All Users', 'target_percentage': 50, }, { 'phase_name': 'General Availability', 'description': 'Full rollout to all users', 'target_audience': '100% of Users', 'target_percentage': 100, } ] for idx, phase_data in enumerate(default_phases, 1): FeaturePhase.objects.create( feature=feature, phase_name=phase_data['phase_name'], description=phase_data['description'], target_audience=phase_data['target_audience'], target_percentage=phase_data['target_percentage'], start_date=timezone.now() + timezone.timedelta(days=idx*7), # 1 week apart ) @staticmethod def approve_rfc(feature, user): """Approve RFC and transition to rollout if all approvers approve""" if feature.state != 'RFC': raise ValidationError("Only RFCs can be approved") feature.rfc_approvers.add(user) # Check if all required approvers have approved required_approvers = Feature.objects.filter( id=feature.id ).values_list('rfc_approvers', flat=True).distinct().count() if feature.rfc_approvers.count() >= required_approvers: FeatureLifecycleService.transition_feature(feature, 'ROLLOUT', user) return feature @staticmethod def update_rollout_progress(feature, phase_name, percentage): """Update rollout percentage for a specific phase""" if feature.state != 'ROLLOUT': raise ValidationError("Only features in rollout can update progress") try: phase = feature.phases.get(phase_name=phase_name) phase.actual_percentage = min(percentage, phase.target_percentage) # Check if phase is complete if phase.actual_percentage >= phase.target_percentage and not phase.is_completed: phase.is_completed = True phase.end_date = timezone.now() phase.save() # Update overall feature rollout percentage total_target = sum(p.target_percentage for p in feature.phases.all()) if total_target > 0: feature.rollout_percentage = min( int(sum(p.actual_percentage for p in feature.phases.all()) / total_target * 100), 100 ) feature.save() # Check if all phases are complete if all(p.is_completed for p in feature.phases.all()): FeatureLifecycleService.transition_feature(feature, 'COMPLETED') except FeaturePhase.DoesNotExist: raise ValidationError(f"Phase '{phase_name}' not found") return feature @staticmethod def schedule_cleanup(feature, cleanup_date=None): """Schedule cleanup for a completed feature""" if feature.state != 'COMPLETED': raise ValidationError("Only completed features can be scheduled for cleanup") feature.cleanup_scheduled_date = cleanup_date or (timezone.now().date() + timezone.timedelta(days=90)) FeatureLifecycleService.transition_feature( feature, 'COMPLETED_CLEANUP_PENDING', cleanup_date=feature.cleanup_scheduled_date ) return feature @staticmethod def complete_cleanup(feature, user, cleanup_notes=None): """Mark cleanup as completed and archive feature""" if feature.state != 'COMPLETED_CLEANUP_PENDING': raise ValidationError("Only features pending cleanup can be completed") feature.cleanup_completed_date = timezone.now() feature.cleanup_notes = cleanup_notes FeatureLifecycleService.transition_feature(feature, 'ARCHIVED', user) return featureAPI Endpoints (Django REST Framework)
# api/views.py from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.response import Response from .models import Feature from .serializers import FeatureSerializer, FeaturePhaseSerializer from .services import FeatureLifecycleService class FeatureViewSet(viewsets.ModelViewSet): queryset = Feature.objects.all() serializer_class = FeatureSerializer @action(detail=True, methods=['post']) def submit_rfc(self, request, pk=None): """Submit RFC document""" feature = self.get_object() rfc_url = request.data.get('rfc_url') if not rfc_url: return Response( {'error': 'RFC URL is required'}, status=status.HTTP_400_BAD_REQUEST ) feature.rfc_url = rfc_url FeatureLifecycleService.transition_feature(feature, 'RFC', request.user) return Response({'status': 'RFC submitted'}) @action(detail=True, methods=['post']) def approve_rfc(self, request, pk=None): """Approve RFC""" feature = self.get_object() FeatureLifecycleService.approve_rfc(feature, request.user) return Response({'status': 'RFC approved'}) @action(detail=True, methods=['post']) def start_rollout(self, request, pk=None): """Manually start rollout (if auto-start not desired)""" feature = self.get_object() FeatureLifecycleService.transition_feature(feature, 'ROLLOUT', request.user) return Response({'status': 'Rollout started'}) @action(detail=True, methods=['post']) def update_rollout(self, request, pk=None): """Update rollout progress""" feature = self.get_object() phase_name = request.data.get('phase_name') percentage = request.data.get('percentage') FeatureLifecycleService.update_rollout_progress(feature, phase_name, percentage) return Response({'status': 'Rollout updated'}) @action(detail=True, methods=['post']) def complete_feature(self, request, pk=None): """Mark feature as completed""" feature = self.get_object() FeatureLifecycleService.transition_feature(feature, 'COMPLETED', request.user) return Response({'status': 'Feature completed'}) @action(detail=True, methods=['post']) def schedule_cleanup(self, request, pk=None): """Schedule cleanup""" feature = self.get_object() cleanup_date = request.data.get('cleanup_date') FeatureLifecycleService.schedule_cleanup(feature, cleanup_date) return Response({'status': 'Cleanup scheduled'}) @action(detail=True, methods=['post']) def complete_cleanup(self, request, pk=None): """Complete cleanup and archive""" feature = self.get_object() notes = request.data.get('notes', '') FeatureLifecycleService.complete_cleanup(feature, request.user, notes) return Response({'status': 'Cleanup completed, feature archived'}) @action(detail=True, methods=['post']) def reject(self, request, pk=None): """Reject feature""" feature = self.get_object() FeatureLifecycleService.transition_feature(feature, 'REJECTED', request.user) return Response({'status': 'Feature rejected'}) @action(detail=False, methods=['get']) def by_state(self, request): """Get features grouped by state""" states = {} for state, _ in Feature.LIFE_CYCLE_STATES: states[state] = Feature.objects.filter(state=state).count() return Response(states)Serializers
# api/serializers.py from rest_framework import serializers from .models import Feature, FeaturePhase, FeatureComment class FeaturePhaseSerializer(serializers.ModelSerializer): class Meta: model = FeaturePhase fields = '__all__' class FeatureCommentSerializer(serializers.ModelSerializer): author_name = serializers.SerializerMethodField() class Meta: model = FeatureComment fields = ['id', 'author_name', 'content', 'created_at', 'is_decision', 'decision_type'] def get_author_name(self, obj): return obj.author.get_full_name() or obj.author.username class FeatureSerializer(serializers.ModelSerializer): phases = FeaturePhaseSerializer(many=True, read_only=True) owner_name = serializers.SerializerMethodField() rfc_approvers_count = serializers.SerializerMethodField() days_in_state = serializers.SerializerMethodField() class Meta: model = Feature fields = '__all__' read_only_fields = ['created_at', 'updated_at'] def get_owner_name(self, obj): return obj.owner.get_full_name() or obj.owner.username def get_rfc_approvers_count(self, obj): return obj.rfc_approvers.count() def get_days_in_state(self, obj): delta = timezone.now() - obj.updated_at return delta.daysScheduled Tasks (Celery)
# tasks.py from celery import shared_task from django.utils import timezone from django.db.models import Q from .models import Feature from .services import FeatureLifecycleService @shared_task def cleanup_scheduled_features(): """Find features ready for cleanup and schedule them""" today = timezone.now().date() # Find features completed for 90+ days that need cleanup features = Feature.objects.filter( state='COMPLETED', cleanup_scheduled_date__lte=today ).exclude( state__in=['COMPLETED_CLEANUP_PENDING', 'ARCHIVED'] ) for feature in features: try: FeatureLifecycleService.transition_feature( feature, 'COMPLETED_CLEANUP_PENDING' ) except Exception as e: # Log error but continue with other features logger.error(f"Failed to schedule cleanup for {feature.name}: {e}") @shared_task def archive_old_features(): """Archive features that have been in cleanup pending too long""" cutoff_date = timezone.now().date() - timezone.timedelta(days=30) features = Feature.objects.filter( state='COMPLETED_CLEANUP_PENDING', cleanup_scheduled_date__lte=cutoff_date ) for feature in features: try: FeatureLifecycleService.complete_cleanup( feature, user=None, # System user cleanup_notes="Auto-archived after 30 days in cleanup pending" ) except Exception as e: logger.error(f"Failed to archive {feature.name}: {e}") @shared_task def check_stale_features(): """Find features stuck in states too long and notify owners""" from datetime import timedelta # Define thresholds (in days) for each state thresholds = { 'PROPOSAL': 30, 'RFC': 14, 'ROLLOUT': 90, # Max time in rollout } for state, threshold in thresholds.items(): cutoff = timezone.now() - timedelta(days=threshold) stale_features = Feature.objects.filter( state=state, updated_at__lte=cutoff ) for feature in stale_features: # Send notification to owner send_stale_feature_notification.delay(feature.id, state, threshold)Management Commands
# management/commands/feature_report.py from django.core.management.base import BaseCommand from django.utils import timezone from features.models import Feature class Command(BaseCommand): help = 'Generate feature lifecycle report' def add_arguments(self, parser): parser.add_argument( '--state', type=str, help='Filter by state' ) parser.add_argument( '--days', type=int, default=30, help='Show features active in last N days' ) def handle(self, *args, **options): cutoff = timezone.now() - timezone.timedelta(days=options['days']) queryset = Feature.objects.filter(updated_at__gte=cutoff) if options['state']: queryset = queryset.filter(state=options['state']) self.stdout.write(f"Found {queryset.count()} features") for feature in queryset: self.stdout.write( f"{feature.name:40} {feature.state:20} " f"Owner: {feature.owner.username:10} " f"Updated: {feature.updated_at.date()}" )Database Indexes & Performance
# Add to models.py Meta class class Feature(models.Model): # ... fields ... class Meta: indexes = [ models.Index(fields=['state', 'updated_at']), models.Index(fields=['owner', 'state']), models.Index(fields=['cleanup_scheduled_date', 'state']), models.Index(fields=['rollout_phase', 'state']), ]Monitoring & Alerts
# monitoring/feature_monitor.py import logging from datetime import timedelta from django.utils import timezone from django.db.models import Count, Q from features.models import Feature logger = logging.getLogger(__name__) class FeatureMonitor: """Monitor feature lifecycle health""" @staticmethod def check_sla_compliance(): """Check if features are moving through states within SLA""" alerts = [] # Features stuck in RFC > 14 days rfc_cutoff = timezone.now() - timedelta(days=14) stuck_rfc = Feature.objects.filter( state='RFC', updated_at__lte=rfc_cutoff ).count() if stuck_rfc > 0: alerts.append(f"{stuck_rfc} features stuck in RFC > 14 days") # Features in rollout > 90 days rollout_cutoff = timezone.now() - timedelta(days=90) long_rollout = Feature.objects.filter( state='ROLLOUT', rollout_start_date__lte=rollout_cutoff ).count() if long_rollout > 0: alerts.append(f"{long_rollout} features in rollout > 90 days") # Features completed but cleanup not started after 120 days cleanup_cutoff = timezone.now() - timedelta(days=120) delayed_cleanup = Feature.objects.filter( state='COMPLETED', cleanup_scheduled_date__isnull=True, rollout_completion_date__lte=cleanup_cutoff ).count() if delayed_cleanup > 0: alerts.append(f"{delayed_cleanup} completed features without cleanup scheduled") return alerts @staticmethod def get_state_distribution(): """Get count of features by state""" return Feature.objects.values('state').annotate(count=Count('id')).order_by('state')Usage Example
# Example workflow from features.services import FeatureLifecycleService from django.contrib.auth.models import User # 1. Create proposal owner = User.objects.get(username='product_manager') feature = FeatureLifecycleService.propose_feature( name="New Dashboard", description="Enhanced analytics dashboard", owner=owner ) # 2. Submit RFC feature.rfc_url = "https://docs.google.com/document/d/123" FeatureLifecycleService.transition_feature(feature, 'RFC', owner) # 3. Approve RFC (multiple approvers) approver1 = User.objects.get(username='tech_lead') approver2 = User.objects.get(username='engineering_manager') FeatureLifecycleService.approve_rfc(feature, approver1) FeatureLifecycleService.approve_rfc(feature, approver2) # 4. Start rollout (auto-transitions to ROLLOUT when RFC approved) # Auto-creates default phases # 5. Update rollout progress FeatureLifecycleService.update_rollout_progress( feature, phase_name='Internal Testing', percentage=100 ) # 6. Complete feature FeatureLifecycleService.transition_feature(feature, 'COMPLETED', owner) # 7. Schedule cleanup (auto-scheduled 90 days, but can be manual) FeatureLifecycleService.schedule_cleanup(feature) # 8. Complete cleanup after 90 days FeatureLifecycleService.complete_cleanup( feature, user=owner, cleanup_notes="Removed old configuration, deleted feature flags, archived data" )Key Features:
- State Machine: Valid transitions with proper validation
- Phased Rollouts: Multi-phase rollout with target percentages
- RFC Process: Document-based approvals with multiple approvers
- Automated Transitions: Auto-scheduling of cleanup 90 days after completion
- Dependency Tracking: Track feature dependencies
- Audit Trail: Comments and decision tracking
- Monitoring: SLA tracking and stale feature detection
- Scheduled Tasks: Automatic cleanup scheduling and archiving
- REST API: Full CRUD with lifecycle actions
- Reporting: State distribution and aging reports
Deployment Considerations:
- Add to
INSTALLED_APPS:'features' - Run migrations:
python manage.py migrate features - Configure Celery for scheduled tasks
- Set up monitoring alerts for SLA violations
- Add webhooks if integrating with external systems (Jira, Slack, etc.)
- Implement RBAC for state transition permissions
- Add feature flag integration to tie rollout percentages to actual flag exposure
This service provides a complete, production-ready feature lifecycle management system with proper state transitions, approvals, phased rollouts, and automated cleanup.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.