We are going to design a feature lifecycle governance engine.
The engine should track artifacts (features, experiments, etc.) through stages: inception, experimentation, GA (General Availability), deprecation, and sunset.
We need to define:
- The core data model for a feature artifact.
- The state machine for the lifecycle (allowed transitions, timestamps, etc.)
- Governance rules (who can approve transitions, required artifacts, SLAs, etc.)
- An audit trail for all state changes.
- Possibly a way to define custom stages (since some organizations might have more stages).
Let's break down:
-
Data Model:
We'll have a Feature (or Artifact) class/table with at least:
- id: unique identifier
- name: human-readable name
- description: what it is
- current_stage: one of the lifecycle stages (but we might want to allow custom stages, so perhaps a separate Stage model)
- created_by: user who created
- created_at: when created
- updated_at: when last updated
- ... other metadata
However, to support custom stages and a flexible lifecycle, we might model stages as a separate entity.
Alternatively, we can have a fixed set of stages but with the ability to add custom ones? Let's assume we want a fixed set of stages for simplicity in the first version, but design for extensibility.
Stages (in order):
- INCEPTION
- EXPERIMENTATION
- GA
- DEPRECATION
- SUNSET
But note: some organizations might have "beta", "rc", etc. So maybe we allow custom stages and define the lifecycle as a directed graph of stages.
Let's design for flexibility:
We have:
- Stage: id, name, description, is_final (boolean, e.g., SUNSET is final), is_initial (boolean, e.g., INCEPTION is initial)
- Transition: from_stage_id, to_stage_id, required_approvers (maybe a list of roles), required_artifacts (like documentation, metrics, etc.), sla_days (max time allowed in the from stage before requiring transition or something? Not exactly. Maybe we have a rule that says you cannot stay in a stage for more than X days without renewal)
However, for simplicity in the first version, we can have a fixed set of stages and define allowed transitions and required approvals per transition in code or config.
Given the complexity, let's start with a fixed set and then make it configurable.
-
State Machine:
We'll define the allowed transitions:
INCEPTION -> EXPERIMENTATION
EXPERIMENTATION -> GA
GA -> DEPRECATION
DEPRECATION -> SUNSET
But also, we might allow skipping? For example, from EXPERIMENTATION directly to DEPRECATION if the experiment fails? That's a business rule.
Let's assume we allow:
INCEPTION -> EXPERIMENTATION
INCEPTION -> DEPRECATION (cancel early)
EXPERIMENTATION -> GA
EXPERIMENTATION -> DEPRECATION
GA -> DEPRECATION
DEPRECATION -> SUNSET
Also, we might want to allow moving backwards? Usually not in a strict lifecycle, but sometimes you might want to revert to a previous stage for a rollback. Let's not allow backwards by default.
So we have a directed acyclic graph (DAG) of stages.
-
Governance Rules:
For each transition, we might require:
- Approval from certain roles (e.g., product manager for INCEPTION->EXPERIMENTATION, engineering lead for EXPERIMENTATION->GA, etc.)
- Required artifacts: e.g., for GA you need a runbook, for deprecation you need a migration plan, etc.
- SLA: maximum time allowed in a stage before the feature must move on or be re-evaluated? Or minimum time? Let's say we have a minimum time in each stage to ensure proper evaluation.
We can model:
TransitionRule:
- from_stage
- to_stage
- required_roles (list of roles that must approve)
- required_artifacts (list of artifact types that must be present)
- min_duration_in_days (minimum time the feature must spend in the from stage before it can transition)
- max_duration_in_days (maximum time allowed in the from stage before it must transition or be abandoned? This might be a warning, not a block)
But note: the min and max duration might be per stage, not per transition? Actually, it's about how long you stay in a stage, so it's a property of the stage? But the allowed transitions are between stages.
Alternatively, we can have:
StagePolicy:
- stage
- min_duration
- max_duration
- required_artifacts (for entering this stage? or for leaving? Let's think: when you are in a stage, you must have certain artifacts. But the artifacts might be required to enter the stage? Actually, the artifacts are produced during the stage and must be present before leaving.
So maybe:
For a transition, we check:
- The feature has been in the from_stage for at least min_duration (if defined for that stage? or for the transition?).
- The feature has the required artifacts (which are defined for the to_stage? or for the transition?).
Let's define:
Stage:
- id, name, description
- is_initial
- is_final
- min_duration (optional, default 0) -> the minimum time a feature must spend in this stage before it can leave.
- max_duration (optional) -> the maximum time a feature can spend in this stage before it must leave (or get an extension?).
Transition:
- from_stage_id, to_stage_id
- required_roles (list of roles that must approve this transition)
- required_artifacts (list of artifact types that must be present in the feature's artifact set to allow the transition)
ArtifactType:
- id, name, description
FeatureArtifact:
- feature_id, artifact_type_id, url (or storage reference), created_at, created_by
Then, when trying to transition a feature from stage A to stage B:
Check:
1. The current stage of the feature is A.
2. There exists a transition from A to B (or if we allow direct transitions without explicit transition record? Maybe we define the allowed transitions in the StagePolicy? Actually, the transition is the edge in the DAG).
3. The feature has been in stage A for at least the min_duration of stage A? Or the min_duration of the transition? I think it's about the stage: you cannot leave a stage too quickly. So we check the stage's min_duration.
4. The feature has all the required artifacts for the transition (or for the destination stage?).
-
Audit Trail:
We need to record every stage change:
FeatureHistory:
- feature_id
- from_stage
- to_stage
- timestamp
- changed_by (user who initiated)
- approvals (list of users who approved, maybe a separate table)
- comments
But approvals might be many-to-many with users and the history entry.
Alternatively, we can have:
FeatureHistory:
- id
- feature_id
- from_stage_id
- to_stage_id
- changed_by_id (user)
- timestamp
- comment
Approval:
- id
- history_entry_id
- user_id
- role (the role that this user approved as, if we have roles per transition)
- approved_at (maybe same as history timestamp? or when they approved)
- comments
But note: the required roles for the transition are defined in the TransitionRule. So when we record the approval, we know which role was required. We can store the role that the approver had at the time of approval? Or just store the user and then we can check if that user had the required role at that time? That might be complex.
Alternatively, we don't store the role in the approval, but we record that the user approved. Then when we check the transition, we check that among the approvals for that history entry, there is at least one user for each required role? But the same user might have multiple roles? Or we require one approval per required role.
Let's simplify: for a transition, we have a set of required roles. We require that for each required role, at least one user with that role (at the time of approval) has approved. But we don't store the role in the approval. Instead, we store the user and then we have a separate UserRole table that is versioned? That's getting complex.
For now, let's assume that the approval is done by a user and we record the user. Then we check that the set of approvers covers the required roles by looking up the user's roles at the time of approval? But we don't store the role in the approval.
Alternatively, we can store the role in the approval. Then we know exactly which role was used for that approval.
So:
Approval:
- history_entry_id
- user_id
- role (the role that this approval counts for, must be one of the required roles for the transition)
- approved_at
Then, when processing a transition, we collect the approvals for that history entry and check that for each required role in the transition, there is at least one approval with that role.
But note: the same user might approve for multiple roles? Probably not, but possible. We'll allow.
-
Implementation:
We'll design classes/interfaces:
class Stage:
id: str
name: str
description: str
is_initial: bool
is_final: bool
min_duration: timedelta (optional)
max_duration: timedelta (optional)
required_artifacts: List[ArtifactType] # required to enter this stage
class Transition:
from_stage: Stage
to_stage: Stage
required_roles: List[str] # list of role names (e.g., "product_manager", "eng_lead")
# Note: we don't have min/max duration here because it's per stage.
class ArtifactType:
id: str
name: str
description: str
class Feature:
id: str
name: str
description: str
current_stage: Stage
created_by: User
created_at: datetime
updated_at: datetime
artifacts: List[FeatureArtifact] # artifacts attached to this feature
class FeatureArtifact:
id: str
feature: Feature
artifact_type: ArtifactType
url: str # or content?
created_by: User
created_at: datetime
class FeatureHistory:
id: str
feature: Feature
from_stage: Stage
to_stage: Stage
changed_by: User
changed_at: datetime
comment: str (optional)
approvals: List[Approval] # the approvals for this transition
class Approval:
id: str
history: FeatureHistory
user: User
role: str # the role that this approval satisfies
approved_at: datetime
We also need a way to define the lifecycle graph (stages and transitions). This can be stored in the database as configuration.
We'll have:
StageConfig (table for Stage)
TransitionConfig (table for Transition, with foreign keys to Stage)
And then we have the actual Feature data and FeatureHistory.
-
Transition Process:
To transition a feature from stage A to stage B:
Step 1: Check that the feature's current stage is A.
Step 2: Check that there exists a transition from A to B (in the TransitionConfig).
Step 3: Check that the feature has been in stage A for at least StageConfig(A).min_duration.
Step 4: Check that the feature does not exceed StageConfig(A).max_duration (if set) -> if exceeded, log a warning but allow? Or require extra approval? Let's say we require an extra approval role for transitions that are past max_duration? We don't have that in the model. Alternatively, we can have a flag in the transition that says "allow_past_max_duration" and if not, then fail. But let's keep it simple: if max_duration is set and time_in_stage > max_duration, then we require an additional approval role "escalation_approver" or something. But that's getting complex.
Instead, let's have:
In the TransitionConfig, we can have:
- required_roles (always required)
- additional_roles_if_past_max_duration (optional list of roles)
Then, if the feature has been in stage A past max_duration, then we require the additional roles as well.
Step 5: Check that the feature has all the required artifacts for entering stage B (from StageConfig(B).required_artifacts). That is, for each artifact type in StageConfig(B).required_artifacts, there must be a FeatureArtifact for this feature of that type.
Step 6: Collect approvals: we need one approval for each role in the required_roles (and if past max_duration, then also for each role in additional_roles_if_past_max_duration). The approvals must be from users with that role at the time of approval? But we are storing the role in the Approval, so we just check that there is an Approval for this transition (which will be created when the transition is executed) with that role.
However, the approvals are given before the transition. So the process:
- User requests transition.
- System checks conditions (1-5).
- System determines the set of required roles for this transition (considering if past max_duration).
- System checks if we have approvals from users with those roles (by looking at Approval records for this transition? But we haven't created the transition history yet). So we need a way to collect approvals before creating the history.
We can have a pending transition request:
TransitionRequest:
- feature_id
- from_stage (A)
- to_stage (B)
- requested_by (user)
- requested_at
- status (pending, approved, rejected, completed)
- required_roles (list of roles) -> computed at request time based on current state and stage A's max_duration.
- approvals: List[Approval] (but Approval would be linked to the TransitionRequest, not the history yet)
Then, when all required roles are approved (and any other conditions are still met? note: the feature might have changed in the meantime? We should re-check at the time of execution), we execute the transition:
- Create FeatureHistory record with from_stage=A, to_stage=B, changed_by=requested_by (or the system?).
- For each approval in the TransitionRequest, create an Approval record linked to the FeatureHistory.
- Update the feature's current_stage to B.
- Mark TransitionRequest as completed.
But note: the condition checks (like min_duration, artifacts) might have changed between request and execution? We should re-check at execution time.
Alternatively, we can do:
- When the last required approval is given, we automatically execute the transition (lazy) and then create the history.
But then the transition might fail if conditions are no longer met. So we need to handle that.
Let's do:
Step 1: User requests transition. System checks conditions and required roles. If conditions are met, create a TransitionRequest with status pending and record the required_roles at that time.
Step 2: Users approve. Each approval is recorded against the TransitionRequest.
Step 3: When the last required approval is received (or an admin forces), we try to execute:
Re-check all conditions (including min_duration, artifacts, and also that the current stage is still A). If any condition fails, the transition fails and we notify.
If all pass, then:
- Create FeatureHistory.
- Create Approval records for each approval in the TransitionRequest, linked to the FeatureHistory.
- Update feature's current_stage.
- Mark TransitionRequest as completed.
This way, we have an audit trail of the request and the approvals.
-
Extensibility:
We want to allow custom stages and transitions. So we store the StageConfig and TransitionConfig in the database.
We can have an admin interface to define stages and transitions.
-
Notifications:
We might want to notify when a feature is about to exceed max_duration, or when a transition is requested, etc.
-
SLA Monitoring:
We can have a background job that checks for features that have been in a stage beyond max_duration and send alerts.
Given the complexity, we'll design the core models and the transition process.
Let's write the models in Python (using SQLAlchemy as an example, but we'll keep it abstract).
However, note: the problem says "Develop a feature lifecycle governance engine". We are designing the engine, so we need to provide the core logic.
We'll write:
- The data models (as classes with fields, but without implementation details of the ORM).
- The transition logic as a service class.
But since we are in a text-based response, we'll describe the design and then provide a simplified implementation in code (pseudocode or Python with SQLAlchemy-like).
Let's code:
We assume we have a User model (with roles, but we'll just store role as a string in the Approval for now).
We'll use SQLAlchemy declarative base.
We'll also assume we have a way to get the current time (datetime.utcnow).
We'll create:
class Stage(Base):
__tablename__ = 'stages'
id = Column(Integer, primary_key=True)
name = Column(String, unique=True, nullable=False)
description = Column(String)
is_initial = Column(Boolean, default=False)
is_final = Column(Boolean, default=False)
min_duration_days = Column(Integer, default=0) # we'll store as days for simplicity
max_duration_days = Column(Integer) # nullable
# required artifacts to enter this stage
required_artifacts = relationship("StageRequiredArtifact", back_populates="stage")
class StageRequiredArtifact(Base):
__tablename__ = 'stage_required_artifacts'
id = Column(Integer, primary_key=True)
stage_id = Column(Integer, ForeignKey('stages.id'))
artifact_type_id = Column(Integer, ForeignKey('artifact_types.id'))
stage = relationship("Stage", back_populates="required_artifacts")
artifact_type = relationship("ArtifactType")
class ArtifactType(Base):
__tablename__ = 'artifact_types'
id = Column(Integer, primary_key=True)
name = Column(String, unique=True, nullable=False)
description = Column(String)
class Transition(Base):
__tablename__ = 'transitions'
id = Column(Integer, primary_key=True)
from_stage_id = Column(Integer, ForeignKey('stages.id'))
to_stage_id = Column(Integer, ForeignKey('stages.id'))
required_roles = Column(String) # comma-separated list of roles, or JSON array? Let's use JSON for flexibility.
from_stage = relationship("Stage", foreign_keys=[from_stage_id])
to_stage = relationship("Stage", foreign_keys=[to_stage_id])
# We can also have additional_roles_if_past_max_duration? Let's add:
additional_roles_if_past_max_duration = Column(String) # JSON array
class Feature(Base):
__tablename__ = 'features'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
description = Column(String)
current_stage_id = Column(Integer, ForeignKey('stages.id'))
created_by_id = Column(Integer, ForeignKey('users.id'))
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
current_stage = relationship("Stage")
created_by = relationship("User")
artifacts = relationship("FeatureArtifact", back_populates="feature")
history = relationship("FeatureHistory", back_populates="feature")
transition_requests = relationship("TransitionRequest", back_populates="feature")
class FeatureArtifact(Base):
__tablename__ = 'feature_artifacts'
id = Column(Integer, primary_key=True)
feature_id = Column(Integer, ForeignKey('features.id'))
artifact_type_id = Column(Integer, ForeignKey('artifact_types.id'))
url = Column(String) # or we can store the content? Let's store a URL.
created_by_id = Column(Integer, ForeignKey('users.id'))
created_at = Column(DateTime, default=datetime.utcnow)
feature = relationship("Feature", back_populates="artifacts")
artifact_type = relationship("ArtifactType")
created_by = relationship("User")
class FeatureHistory(Base):
__tablename__ = 'feature_history'
id = Column(Integer, primary_key=True)
feature_id = Column(Integer, ForeignKey('features.id'))
from_stage_id = Column(Integer, ForeignKey('stages.id'))
to_stage_id = Column(Integer, ForeignKey('stages.id'))
changed_by_id = Column(Integer, ForeignKey('users.id'))
changed_at = Column(DateTime, default=datetime.utcnow)
comment = Column(String)
feature = relationship("Feature", back_populates="history")
from_stage = relationship("Stage", foreign_keys=[from_stage_id])
to_stage = relationship("Stage", foreign_keys=[to_stage_id])
changed_by = relationship("User")
approvals = relationship("Approval", back_populates="history")
class TransitionRequest(Base):
__tablename__ = 'transition_requests'
id = Column(Integer, primary_key=True)
feature_id = Column(Integer, ForeignKey('features.id'))
from_stage_id = Column(Integer, ForeignKey('stages.id'))
to_stage_id = Column(Integer, ForeignKey('stages.id'))
requested_by_id = Column(Integer, ForeignKey('users.id'))
requested_at = Column(DateTime, default=datetime.utcnow)
status = Column(String, default='pending') # pending, approved, rejected, completed
required_roles_snapshot = Column(String) # JSON array of roles that were required at request time (because the transition config might change)
additional_roles_snapshot = Column(String) # JSON array for additional roles if past max_duration at request time
feature = relationship("Feature", back_populates="transition_requests")
from_stage = relationship("Stage", foreign_keys=[from_stage_id])
to_stage = relationship("Stage", foreign_keys=[to_stage_id])
requested_by = relationship("User")
approvals = relationship("RequestApproval", back_populates="transition_request")
class RequestApproval(Base):
__tablename__ = 'request_approvals'
id = Column(Integer, primary_key=True)
transition_request_id = Column(Integer, ForeignKey('transition_requests.id'))
user_id = Column(Integer, ForeignKey('users.id'))
role = Column(String) # the role that this approval satisfies (must be in the required_roles_snapshot of the request)
approved_at = Column(DateTime, default=datetime.utcnow)
comment = Column(String)
transition_request = relationship("TransitionRequest", back_populates="approvals")
user = relationship("User")
class Approval(Base):
__tablename__ = 'approvals'
id = Column(Integer, primary_key=True)
history_id = Column(Integer, ForeignKey('feature_history.id'))
user_id = Column(Integer, ForeignKey('users.id'))
role = Column(String) # the role that this approval satisfies (must be in the transition's required_roles)
approved_at = Column(DateTime, default=datetime.utcnow)
history = relationship("FeatureHistory", back_populates="approvals")
user = relationship("User")
10. The Transition Service:
We'll have a class FeatureLifecycleService with methods:
request_transition(feature_id, to_stage_id, requested_by_user_id, comment=None):
- Check if the feature exists and current_stage is set.
- Check if there is a transition from current_stage to to_stage_id.
- Get the Stage for current_stage (from_stage) and the Stage for to_stage (to_stage).
- Check min_duration: time_in_stage = now - feature.updated_at (or we might have a separate field for when the stage changed? We don't have that. We have updated_at, but that updates on any change. We need a stage_changed_at field in Feature? Let's add:
stage_changed_at = Column(DateTime, default=datetime.utcnow) # set when the current_stage is updated.
- Then time_in_stage = now - feature.stage_changed_at.
- If time_in_stage < from_stage.min_duration_days (converted to timedelta), then fail.
- Check if from_stage.max_duration_days is set and time_in_stage > from_stage.max_duration_days (as timedelta). If so, then we will need additional roles (from the transition's additional_roles_if_past_max_duration).
- Check required artifacts: get the list of artifact types from to_stage.required_artifacts. For each, check that there is a FeatureArtifact for this feature of that type.
- Get the required roles from the transition (transition.required_roles) and if past max_duration, also get the additional roles (transition.additional_roles_if_past_max_duration). Combine.
- Create a TransitionRequest with:
feature_id, from_stage_id (current_stage_id), to_stage_id, requested_by_id, status='pending',
required_roles_snapshot = JSON of the required roles (including additional if any),
additional_roles_snapshot = JSON of the additional roles (if any).
- Return the TransitionRequest.
approve_transition_request(request_id, user_id, role, comment=None):
- Get the TransitionRequest.
- Check that the request is pending.
- Check that the user is allowed to approve with the given role? We might check that the user has that role (but we don't have a user-role table in our model? We have only stored the role in the approval. We might need to have a UserRole table to know what roles a user has at a given time? But for simplicity, we assume that the user can only approve for roles they currently have? And we store the role they approved as.
- Create a RequestApproval with transition_request_id, user_id, role, approved_at=now.
- Then check if all required roles (from request.required_roles_snapshot) have been approved (i.e., there exists a RequestApproval for this request with that role). If yes, then we can try to execute the transition.
- But note: the required_roles_snapshot is a list, and we need one approval for each role? Or at least one approval from a user with that role? We have stored the role in the approval, so we check that for each role in required_roles_snapshot, there is at least one RequestApproval with that role.
- Then, call execute_transition(request_id).
execute_transition(request_id):
- Get the TransitionRequest.
- Re-check all conditions (because they might have changed since request):
- Feature still exists and current_stage is the from_stage of the request.
- The transition from current_stage to to_stage is still allowed (the TransitionConfig might have changed? We are using the snapshot, but we should also check that the transition is still defined? Actually, we are using the snapshot of required roles, but the existence of the transition is stage-level? We should check that the transition from current_stage to to_stage is still defined? But if the transition was deleted, we might not want to allow. But we have the snapshot of required roles, so we might allow? Let's not check the transition config again? But we should check that the to_stage still exists and the from_stage still exists? They are stored in the request.
- Check min_duration again (with current stage_changed_at).
- Check artifacts again (the feature might have added/removed artifacts).
- Check if we are past max_duration again? But we have the snapshot of additional roles? Actually, we might have been past max_duration at request time, but now we are not? That's okay, we still require the additional roles because they were required at request time? Or we re-evaluate? Let's re-evaluate: if at execution time we are not past max_duration, then we don't require the additional roles? But we already got approvals for them. It's okay to have extra approvals.
- But note: the required roles might have changed in the transition config? We have a snapshot, so we use that.
- So we use the snapshot of required roles and additional roles.
- Then, check that for each role in required_roles_snapshot, there is at least one RequestApproval for this request with that role.
- If all conditions pass, then:
- Create FeatureHistory:
feature_id, from_stage_id (request.from_stage_id), to_stage_id (request.to_stage_id), changed_by_id (request.requested_by_id), changed_at=now, comment=request.comment?
- For each RequestApproval for this request, create an Approval record linked to the FeatureHistory (copying the user_id and role, and approved_at from the RequestApproval? But the RequestApproval has approved_at, we can use that).
- Update the feature:
current_stage_id = to_stage_id
stage_changed_at = now
updated_at = now
- Mark the TransitionRequest as completed.
- If any condition fails, mark the TransitionRequest as failed and notify.
reject_transition_request(request_id, user_id, comment=None):
- Mark as rejected.
We also need a way to get the current state of a feature and the allowed transitions, and the required artifacts and roles for a transition.
This is a simplified version.
11. Additional considerations:
- Concurrency: two requests for the same feature? We should lock the feature row when executing the transition.
- We might want to have a way to force a transition (admin override) that bypasses some checks? Not in the first version.
- We might want to have a way to define the required artifacts for a stage as optional? But we are requiring them all.
- We might want to have a way to have a transition that doesn't require any artifacts? Then the stage's required_artifacts can be empty.
- We might want to have a way to have a transition that doesn't require any approvals? Then the transition.required_roles can be empty.
- We might want to have a way to have a transition that is allowed even if the min_duration is not met? That would be an exception. We don't have that.
- We might want to have a way to extend the max_duration? That would be a separate process.
Given the complexity, we'll stop here and provide the code for the models and the transition service with the above logic.
Let's write the code in a simplified way, without all the relationships and with some assumptions.
Note: We are using SQLAlchemy, but we won't define the full relationship mappings for brevity.
We'll define the models and then the service.
However, note: the problem says "Develop a feature lifecycle governance engine". We are providing the design and a basic implementation.
We'll write:
- The models (with columns and relationships, but we might skip some relationships for brevity).
- The service class with the main methods.
But note: the code might be long. We'll try to be concise.
Let's start with the models (only the important fields and relationships):
We assume we have a Base from sqlalchemy.ext.declarative.
We'll define:
class Stage(Base):
__tablename__ = 'stages'
id = Column(Integer, primary_key=True)
name = Column(String, unique=True, nullable=False)
min_duration_days = Column(Integer, default=0)
max_duration_days = Column(Integer)
class ArtifactType(Base):
__tablename__ = 'artifact_types'
id = Column(Integer, primary_key=True)
name = Column(String, unique=True, nullable=False)
class StageRequiredArtifact(Base):
__tablename__ = 'stage_required_artifacts'
id = Column(Integer, primary_key=True)
stage_id = Column(Integer, ForeignKey('stages.id'))
artifact_type_id = Column(Integer, ForeignKey('artifact_types.id'))
class Transition(Base):
__tablename__ = 'transitions'
id = Column(Integer, primary_key=True)
from_stage_id = Column(Integer, ForeignKey('stages.id'))
to_stage_id = Column(Integer, ForeignKey('stages.id'))
required_roles = Column(String) # JSON array
additional_roles_if_past_max_duration = Column(String) # JSON array
class Feature(Base):
__tablename__ = 'features'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
current_stage_id = Column(Integer, ForeignKey('stages.id'))
stage_changed_at = Column(DateTime, default=datetime.utcnow)
created_by_id = Column(Integer, ForeignKey('users.id'))
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class FeatureArtifact(Base):
__tablename__ = 'feature_artifacts'
id = Column(Integer, primary_key=True)
feature_id = Column(Integer, ForeignKey('features.id'))
artifact_type_id = Column(Integer, ForeignKey('artifact_types.id'))
url = Column(String)
created_by_id = Column(Integer, ForeignKey('users.id'))
created_at = Column(DateTime, default=datetime.utcnow)
class FeatureHistory(Base):
__tablename__ = 'feature_history'
id = Column(Integer, primary_key=True)
feature_id = Column(Integer, ForeignKey('features.id'))
from_stage_id = Column(Integer, ForeignKey('stages.id'))
to_stage_id = Column(Integer, ForeignKey('stages.id'))
changed_by_id = Column(Integer, ForeignKey('users.id'))
changed_at = Column(DateTime, default=datetime.utcnow)
comment = Column(String)
class TransitionRequest(Base):
__tablename__ = 'transition_requests'
id = Column(Integer, primary_key=True)
feature_id = Column(Integer, ForeignKey('features.id'))
from_stage_id = Column(Integer, ForeignKey('stages.id'))
to_stage_id = Column(Integer, ForeignKey('stages.id'))
requested_by_id = Column(Integer, ForeignKey('users.id'))
requested_at = Column(DateTime, default=datetime.utcnow)
status = Column(String, default='pending')
required_roles_snapshot = Column(String) # JSON
additional_roles_snapshot = Column(String) # JSON
class RequestApproval(Base):
__tablename__ = 'request_approvals'
id = Column(Integer, primary_key=True)
transition_request_id = Column(Integer, ForeignKey('transition_requests.id'))
user_id = Column(Integer, ForeignKey('users.id'))
role = Column(String)
approved_at = Column(DateTime, default=datetime.utcnow)
class Approval(Base):
__tablename__ = 'approvals'
id = Column(Integer, primary_key=True)
history_id = Column(Integer, ForeignKey('feature_history.id'))
user_id = Column(Integer, ForeignKey('users.id'))
role = Column(String)
approved_at = Column(DateTime, default=datetime.utcnow)
We assume a User model exists.
-
The Service:
We'll create a class FeatureLifecycleService that takes a database session.
We'll implement:
request_transition(self, feature_id, to_stage_id, requested_by_id, comment=None)
approve_transition_request(self, request_id, user_id, role, comment=None)
execute_transition(self, request_id) # internal
reject_transition_request(self, request_id, user_id, comment=None)
We'll also have helper methods:
_get_transition_config(self, from_stage_id, to_stage_id) -> Transition or None
_check_min_duration(self, feature, from_stage) -> bool
_check_artifacts(self, feature, to_stage) -> bool
_get_required_roles(self, transition, from_stage, feature) -> (required_roles, additional_roles) # considering max_duration
Let's code accordingly.
-
Note: We are storing JSON strings for required_roles and additional_roles. We'll use json.loads to parse.
-
We assume that the Stage.required_artifacts relationship gives us the list of StageRequiredArtifact, and then we can get the artifact_type.
-
We assume that the current_stage of the feature is set and valid.
-
We assume that the timezone is UTC.
Let's write the service class:
We'll use a session and we'll need to query.
We'll also need to handle exceptions and rollbacks.
We'll try to be atomic.
We'll use:
with session.begin():
... all operations ...
But note: the approve_transition_request might be called multiple times (by multiple approvers) and then we check if we have all required roles and then execute. So we might have multiple transactions.
We'll do:
In approve_transition_request:
- We add the RequestApproval.
- Then we check if all required roles are approved.
- If yes, we call execute_transition in the same transaction? But execute_transition might take time and we don't want to block the approval. We can mark the request as ready for execution and then have a separate process? Or we can execute immediately.
However, if we execute immediately, then the feature might be updated and the transition request completed, all in one transaction. That's okay.
But what if two approvals come at the same time? We might have a race condition. We should lock the TransitionRequest row.
Alternatively, we can have a background job that picks up pending requests that have all approvals and then executes them.
For simplicity, we'll do:
In approve_transition_request, after adding the approval, we check if the request now has all required roles. If yes, we call execute_transition in the same transaction.
But then if two approvals come at the same time, we might try to execute twice. We can have a status field that we update to 'completed' only once.
So:
In execute_transition, we first check that the request is still in 'pending' status and that all required roles are approved. Then we do the transition and set status to 'completed'.
But we are already in a transaction in approve_transition_request. So we can do:
with session.begin():
# add approval
# then check if all required roles are met (query the RequestApproval for this request and compare with required_roles_snapshot)
# if met, then call execute_transition (which will also be in the same transaction)
However, execute_transition will try to update the feature and create history. That's okay.
But what if the execute_transition fails (because of a condition check)? Then we rollback the approval? Actually, we added the approval but then the transition fails. We want to keep the approval but not complete the transition. So we should not rollback the approval. We should let the approval remain and then the transition remains pending until someone fixes the issue and maybe re-approves? Or we can have a way to re-request?
Alternatively, we can separate the approval collection from the execution. So:
approve_transition_request just records the approval.
Then, we have a separate method `process_ready_requests` that runs periodically and tries to execute any pending request that has all required approvals.
That way, we avoid the race condition and also we can handle failures without losing approvals.
But for simplicity, we'll do:
In approve_transition_request, after adding the approval, we check if the request now has all required roles. If yes, we try to execute the transition. If the transition fails (due to condition checks), we mark the request as 'failed' and maybe notify. The approvals remain.
Then, if the conditions are fixed (e.g., someone adds the missing artifact), then we can have a way to re-check? Not in the first version.
Alternatively, we can have an admin re-request? Or we can have a button to retry.
For now, if the transition fails, the request is stuck. We might need a manual intervention.
So let's do:
In approve_transition_request:
Add the approval.
Then check if we have all required roles (by querying the RequestApproval for this request and comparing with required_roles_snapshot). If not, return.
If we have all, then we try to execute_transition. If execute_transition succeeds, set request.status='completed'. If it fails, set request.status='failed' and log the error.
Then, we can have a method `retry_transition_request(request_id)` that tries again.
But note: the required_roles_snapshot might be outdated? We are using the snapshot from the request. That's okay because the required roles are fixed at request time? But if the transition config changed, we are using the snapshot. So we are safe.
However, the condition checks (min_duration, artifacts) are current at execution time.
So the flow:
request_transition: creates a pending request with snapshot of required roles (and additional roles if any at request time).
approve_transition_request: adds an approval and if all required roles (from snapshot) are approved, then tries to execute.
execute_transition: does the current state checks (min_duration, artifacts) and if pass, does the transition.
This seems okay.
17. Let's code the service:
We assume we have a session and we are using it in each method? Or we pass the session to the service.
We'll design:
class FeatureLifecycleService:
def __init__(self, session):
self.session = session
def request_transition(self, feature_id, to_stage_id, requested_by_id, comment=None):
# ... implementation ...
def approve_transition_request(self, request_id, user_id, role, comment=None):
# ... implementation ...
def execute_transition(self, request_id):
# ... implementation ...
def _get_transition_config(self, from_stage_id, to_stage_id):
# query Transition table
pass
def _check_min_duration(self, feature, from_stage):
# feature.stage_changed_at is a datetime
# from_stage.min_duration_days is an integer (days)
now = datetime.utcnow()
time_in_stage = now - feature.stage_changed_at
min_duration = timedelta(days=from_stage.min_duration_days)
return time_in_stage >= min_duration
def _check_artifacts(self, feature, to_stage):
# get the required artifact types for to_stage
required_artifact_types = [sar.artifact_type for sar in to_stage.required_artifacts]
# get the feature's artifacts
feature_artifact_types = [fa.artifact_type for fa in feature.artifacts]
# check that every required artifact type is in feature_artifact_types
for art_type in required_artifact_types:
if art_type not in feature_artifact_types:
return False
return True
def _get_required_roles_for_request(self, transition, from_stage, feature):
# transition is the Transition object (from config) for from_stage to to_stage.
# But note: we might not have the transition if we are using the snapshot? Actually, in request_transition we get the transition and then snapshot the roles.
# In execute_transition, we use the snapshot from the request, so we don't need to look up the transition again? But we do need to check if the transition still exists? We don't have to because we are using the snapshot.
# However, in request_transition, we need to compute the required roles at that time.
# So:
required_roles = json.loads(transition.required_roles) # assuming stored as JSON string
# Check if we are past max_duration of from_stage
now = datetime.utcnow()
time_in_stage = now - feature.stage_changed_at
if from_stage.max_duration_days is not None:
max_duration = timedelta(days=from_stage.max_duration_days)
if time_in_stage > max_duration:
additional_roles = json.loads(transition.additional_roles_if_past_max_duration) if transition.additional_roles_if_past_max_duration else []
required_roles.extend(additional_roles)
# We might have duplicates? We can set to unique.
required_roles = list(set(required_roles))
additional_roles = [] # we don't need to return additional separately because we already added them to required_roles.
return required_roles
But note: in request_transition, we want to snapshot the required roles (including additional if past max_duration). So we compute the required_roles at that time and store in the request.
In execute_transition, we don't need to compute again because we have the snapshot.
However, in execute_transition we do need to check the current min_duration and artifacts, but not the roles? The roles are already approved.
So:
In request_transition:
transition = self._get_transition_config(current_stage_id, to_stage_id)
if not transition:
raise Exception("Transition not defined")
from_stage = current_stage # we have it from feature.current_stage
required_roles = self._get_required_roles_for_request(transition, from_stage, feature)
then create TransitionRequest with required_roles_snapshot = json.dumps(required_roles)
In execute_transition:
We use the required_roles_snapshot from the request to check if we have approvals.
But we don't use the transition config again.
However, what if the transition config changed and the snapshot is outdated? We are using the snapshot, so it's consistent.
18. Let's code the methods:
We assume the following:
- The Stage model has a relationship `required_artifacts` that gives a list of StageRequiredArtifact objects, and each has an `artifact_type` relationship.
- The Feature model has a relationship `artifacts` that gives FeatureArtifact objects, and each has an `artifact_type`.
- The User model exists.
- We are using JSON for storing lists.
We'll write:
import json
from datetime import datetime, timedelta
class FeatureLifecycleService:
def __init__(self, session):
self.session = session
def request_transition(self, feature_id, to_stage_id, requested_by_id, comment=None):
feature = self.session.query(Feature).get(feature_id)
if not feature:
raise ValueError("Feature not found")
to_stage = self.session.query(Stage).get(to_stage_id)
if not to_stage:
raise ValueError("Stage not found")
from_stage = feature.current_stage
if not from_stage:
raise ValueError("Feature has no current stage")
# Check if transition is defined
transition = self._get_transition_config(from_stage.id, to_stage_id)
if not transition:
raise ValueError(f"No transition defined from {from_stage.name} to {to_stage.name}")
# Check min_duration
if not self._check_min_duration(feature, from_stage):
min_days = from_stage.min_duration_days
raise ValueError(f"Feature must be in stage {from_stage.name} for at least {min_days} days")
# Check artifacts
if not self._check_artifacts(feature, to_stage):
required_artifacts = [sar.artifact_type.name for sar in to_stage.required_artifacts]
raise ValueError(f"Missing required artifacts: {required_artifacts}")
# Compute required roles (considering max_duration)
required_roles = self._get_required_roles_for_request(transition, from_stage, feature)
# Create TransitionRequest
request = TransitionRequest(
feature_id=feature_id,
from_stage_id=from_stage.id,
to_stage_id=to_stage_id,
requested_by_id=requested_by_id,
status='pending',
required_roles_snapshot=json.dumps(required_roles),
additional_roles_snapshot=json.dumps([]) # we don't store separately because we already added to required_roles
)
self.session.add(request)
self.session.commit()
return request
def approve_transition_request(self, request_id, user_id, role, comment=None):
request = self.session.query(TransitionRequest).get(request_id)
if not request:
raise ValueError("Transition request not found")
if request.status != 'pending':
raise ValueError(f"Transition request is not pending (status: {request.status})")
# Check that the role is in the required_roles_snapshot? We can check, but even if not, we record it. But then it won't count towards the required roles? We should only allow approving for roles that are required? Or let the user approve for any role and then when checking we only look for required roles? We'll allow, but only required roles count.
# Create RequestApproval
approval = RequestApproval(
transition_request_id=request_id,
user_id=user_id,
role=role,
approved_at=datetime.utcnow()
)
self.session.add(approval)
self.session.commit()
# Check if we now have all required roles
required_roles = set(json.loads(request.required_roles_snapshot))
# Get all approvals for this request
approvals = self.session.query(RequestApproval).filter_by(transition_request_id=request_id).all()
approved_roles = set([a.role for a in approvals])
if required_roles.issubset(approved_roles):
# All required roles are approved, try to execute
try:
self.execute_transition(request_id)
except Exception as e:
# Mark request as failed?
request.status = 'failed'
self.session.commit()
raise e
return approval
def execute_transition(self, request_id):
request = self.session.query(TransitionRequest).get(request_id)
if not request:
raise ValueError("Transition request not found")
if request.status != 'pending':
raise ValueError(f"Transition request is not pending (status: {request.status})")
# We are going to do everything in a transaction
with self.session.begin():
# Re-fetch the feature and stages to get current state
feature = self.session.query(Feature).get(request.feature_id)
from_stage = self.session.query(Stage).get(request.from_stage_id)
to_stage = self.session.query(Stage).get(request.to_stage_id)
# Check that feature is still in from_stage
if feature.current_stage_id != from_stage.id:
raise ValueError("Feature's current stage has changed")
# Check min_duration again
if not self._check_min_duration(feature, from_stage):
raise ValueError("No longer meets min_duration requirement")
# Check artifacts again
if not self._check_artifacts(feature, to_stage):
raise ValueError("Missing required artifacts for the target stage")
# Check that we have all required roles (from snapshot) approved
required_roles = set(json.loads(request.required_roles_snapshot))
approvals = self.session.query(RequestApproval).filter_by(transition_request_id=request_id).all()
approved_roles = set([a.role for a in approvals])
if not required_roles.issubset(approved_roles):
raise ValueError("Not all required roles have been approved")
# Create FeatureHistory
history = FeatureHistory(
feature_id=feature.id,
from_stage_id=from_stage.id,
to_stage_id=to_stage.id,
changed_by_id=request.requested_by_id,
changed_at=datetime.utcnow(),
comment=request.comment # or we can have a separate comment for the transition?
)
self.session.add(history)
self.session.flush() # to get history.id
# Copy approvals to Approval table
for req_approval in approvals:
# Only copy the ones that are in required_roles? We can copy all, but the history should only have the ones that are required? Or we can copy all and then when we check we only look at the ones that are in the required roles? Actually, the required roles are the ones that were required. We can copy only the ones that are in required_roles? But what if there are extra approvals? They are not necessary. We can copy all, but then when we check the history we only consider the required roles? Or we can copy only the ones that are in required_roles.
# Let's copy only the ones that are in required_roles.
if req_approval.role in required_roles:
approval = Approval(
history_id=history.id,
user_id=req_approval.user_id,
role=req_approval.role,
approved_at=req_approval.approved_at
)
self.session.add(approval)
# Update feature
feature.current_stage_id = to_stage.id
feature.stage_changed_at = datetime.utcnow()
feature.updated_at = datetime.utcnow()
# Update request
request.status = 'completed'
self.session.commit()
def _get_transition_config(self, from_stage_id, to_stage_id):
return self.session.query(Transition).filter_by(
from_stage_id=from_stage_id,
to_stage_id=to_stage_id
).first()
# ... other helper methods ...
This is a basic implementation.
19. Limitations:
- We don't handle the case where the transition config changes after the request is made. We use the snapshot, so it's safe.
- We don't have a way to re-request after a failure. We can add a method `reset_transition_request` that sets status back to pending.
- We don't have a way to add comments during approval? We have a comment in RequestApproval.
- We don't have a way to reject a request. We can add:
def reject_transition_request(self, request_id, user_id, comment=None):
request = self.session.query(TransitionRequest).get(request_id)
request.status = 'rejected'
# maybe store who rejected? We don't have a field for rejected_by. We can add.
self.session.commit()
- We don't have a way to see the current state of a feature and the allowed transitions. We can add:
def get_allowed_transitions(self, feature_id):
feature = self.session.query(Feature).get(feature_id)
current_stage = feature.current_stage
transitions = self.session.query(Transition).filter_by(from_stage_id=current_stage.id).all()
return transitions
def get_required_artifacts_for_stage(self, stage_id):
stage = self.session.query(Stage).get(stage_id)
return [sar.artifact_type for sar in stage.required_artifacts]
- We don't have a way to list the required roles for a transition? We can get that from the Transition object.
- We don't have a way to handle exceptions in execute_transition gracefully. We raise and then in approve_transition_request we catch and mark as failed.
- We are using a single session in the service. We might want to use separate sessions for each request? But for simplicity, we pass the session.
20. This is a starting point. In a real system, we would need more error handling, logging, monitoring, and possibly asynchronous processing.
Given the complexity and the fact that we are in a text-based response, we'll stop here.
We have designed a flexible lifecycle governance engine with:
- Configurable stages and transitions.
- Governance rules: required roles, required artifacts, min duration in stage.
- Approval workflow with snapshot of requirements at request time.
- Audit trail (FeatureHistory and Approval).
- Enforcement of rules at transition time.
We can extend by:
- Adding more governance rules (e.g., required metrics, SLA for max duration with warnings).
- Adding a UI and API.
- Adding notifications.
- Adding a background job to monitor features that are stuck in a stage beyond max_duration.
But this should be a solid foundation.
I'll design a comprehensive Feature Lifecycle Governance Engine that tracks artifacts through their entire lifecycle with robust governance controls.
Architecture Overview
graph TB
A[Feature Lifecycle Engine] --> B[Lifecycle State Machine]
A --> C[Governance Rules Engine]
A --> D[Artifact Registry]
A --> E[Approval Workflows]
A --> F[Audit & Compliance]
B --> B1[Inception]
B --> B2[Experimentation]
B --> B3[GA]
B --> B4[Deprecation]
B --> B5[Sunset]
C --> C1[Role-Based Access]
C --> C2[SLA Monitoring]
C --> C3[Policy Validation]
C --> C4[Risk Assessment]
D --> D1[Metadata Store]
D --> D2[Artifact Versions]
D --> D3[Dependency Graph]
E --> E1[Multi-Level Approvals]
E --> E2[Stakeholder Reviews]
E --> E3[Automated Checks]
F --> F1[Immutable Logs]
F --> F2[Compliance Reports]
F --> F3[Retention Policies]
Core Data Models
1. Feature Artifact Model
class FeatureArtifact(BaseModel):
"""Core artifact representing a feature through its lifecycle"""
id: UUID4
name: str
description: str
taxonomy: FeatureTaxonomy # product area, domain, etc.
# Lifecycle tracking
current_stage: LifecycleStage
stage_effective_date: datetime
stage_history: List[StageTransition] # immutable audit trail
# Metadata
owner: UserReference
stakeholders: List[UserReference]
tags: List[str]
dependencies: List[UUID4] # other feature IDs
documentation_urls: Dict[str, str] # spec, design, runbook, etc.
# Technical details
implementation_team: str
code_location: RepositoryRef
rollout_plan: RolloutPlan
rollback_plan: RollbackPlan
monitoring_setup: MonitoringConfig
# Governance
risk_level: RiskLevel # LOW, MEDIUM, HIGH, CRITICAL
compliance_flags: Set[ComplianceFramework]
approval_requirements: List[ApprovalRequirement]
# Dates
created_date: datetime
last_modified: datetime
planned_sunset_date: Optional[datetime]
# Status flags
is_archived: bool = False
requires_renewal: bool = False
2. Lifecycle Stage Definition
class LifecycleStage(Enum):
INCEPTION = "inception"
EXPERIMENTATION = "experimentation"
LIMITED_AVAILABILITY = "limited_availability"
GENERAL_AVAILABILITY = "general_availability"
DEPRECATION_ANNOUNCED = "deprecation_announced"
DEPRECATION_IN_PROGRESS = "deprecation_in_progress"
SUNSET = "sunset"
ARCHIVED = "archived"
class StageTransition(BaseModel):
"""Immutable record of a stage change"""
from_stage: LifecycleStage
to_stage: LifecycleStage
transition_date: datetime
initiated_by: UserReference
approvals: List[ApprovalRecord]
metadata: Dict[str, Any] # context for transition
compliance_check_results: Dict[str, bool]
3. Governance Policy Model
class GovernancePolicy(BaseModel):
"""Rules that govern stage transitions"""
id: UUID4
name: str
description: str
applicable_stages: List[LifecycleStage]
applicable_taxonomies: List[str] # optional filter by product area
# Conditions
requires_approval_roles: List[Role]
required_artifacts: List[ArtifactType] # spec, metrics, runbook, etc.
min_tenure_days: Optional[int] # min time in current stage
max_tenure_days: Optional[int] # max allowed before forced review
# SLAs
approval_sla_hours: int
documentation_sla_days: int
# Risk controls
risk_assessment_required: bool
compliance_frameworks: List[ComplianceFramework]
# Validation rules (executable)
custom_validators: List[str] # function references
# Enforcement
is_mandatory: bool
failure_action: FailureAction # BLOCK, WARN, ESCALATE
Lifecycle State Machine
class LifecycleStateMachine:
"""Validates and executes stage transitions"""
# Allowed transitions
TRANSITIONS = {
LifecycleStage.INCEPTION: [
LifecycleStage.EXPERIMENTATION,
LifecycleStage.LIMITED_AVAILABILITY # fast-track
],
LifecycleStage.EXPERIMENTATION: [
LifecycleStage.GENERAL_AVAILABILITY,
LifecycleStage.DEPRECATION_ANNOUNCED # experiment failed
],
LifecycleStage.LIMITED_AVAILABILITY: [
LifecycleStage.GENERAL_AVAILABILITY,
LifecycleStage.DEPRECATION_ANNOUNCED
],
LifecycleStage.GENERAL_AVAILABILITY: [
LifecycleStage.DEPRECATION_ANNOUNCED
],
LifecycleStage.DEPRECATION_ANNOUNCED: [
LifecycleStage.DEPRECATION_IN_PROGRESS
],
LifecycleStage.DEPRECATION_IN_PROGRESS: [
LifecycleStage.SUNSET
],
LifecycleStage.SUNSET: [
LifecycleStage.ARCHIVED
]
}
def can_transition(
self,
current: LifecycleStage,
target: LifecycleStage,
feature: FeatureArtifact
) -> TransitionValidation:
"""Check if transition is valid"""
validation = TransitionValidation()
# 1. Check allowed transition
if target not in self.TRANSITIONS.get(current, []):
validation.add_error(f"Invalid transition from {current} to {target}")
return validation
# 2. Check governance policies
applicable_policies = self._get_applicable_policies(current, target, feature)
for policy in applicable_policies:
policy_check = self._validate_policy(policy, feature)
validation.merge(policy_check)
# 3. Check stage-specific requirements
stage_check = self._validate_stage_requirements(target, feature)
validation.merge(stage_check)
# 4. Check dependency constraints
dep_check = self._validate_dependencies(target, feature)
validation.merge(dep_check)
return validation
def transition(
self,
feature_id: UUID4,
target_stage: LifecycleStage,
initiated_by: UserReference,
approvals: List[Approval]
) -> FeatureArtifact:
"""Execute stage transition with full audit trail"""
with self._transaction():
# Load feature with lock
feature = self._lock_feature(feature_id)
# Validate transition
validation = self.can_transition(
feature.current_stage,
target_stage,
feature
)
if not validation.is_valid:
raise TransitionBlockedError(validation.errors)
# Create transition record
transition = StageTransition(
from_stage=feature.current_stage,
to_stage=target_stage,
transition_date=datetime.utcnow(),
initiated_by=initiated_by,
approvals=approvals,
compliance_check_results=validation.compliance_results
)
# Update feature
feature.current_stage = target_stage
feature.stage_effective_date = transition.transition_date
feature.stage_history.append(transition)
feature.last_modified = datetime.utcnow()
# Trigger stage-specific actions
self._execute_stage_hooks(target_stage, feature)
# Emit event
self._publish_event(
EventType.FEATURE_STAGE_CHANGED,
{
"feature_id": feature_id,
"from_stage": feature.current_stage,
"to_stage": target_stage,
"transition": transition.dict()
}
)
return feature
Governance Rules Engine
class GovernanceEngine:
"""Validates feature against all applicable policies"""
def validate_for_stage(
self,
feature: FeatureArtifact,
target_stage: LifecycleStage
) -> ValidationResult:
"""Comprehensive validation before stage transition"""
result = ValidationResult()
# Get all applicable policies
policies = self._get_active_policies(target_stage, feature.taxonomy)
for policy in policies:
# Check mandatory requirements
if policy.is_mandatory:
check = self._check_mandatory_policy(policy, feature)
result.merge(check)
if not check.is_valid and policy.failure_action == FailureAction.BLOCK:
result.add_critical(policy.name, check.errors)
# Check SLAs
sla_check = self._check_sla_compliance(policy, feature)
if not sla_check.is_compliant:
result.add_warning(f"SLA Violation: {policy.name}", sla_check.violations)
# Risk assessment for high-risk features
if feature.risk_level in [RiskLevel.HIGH, RiskLevel.CRITICAL]:
risk_check = self._assess_risk(feature, target_stage)
result.merge(risk_check)
return result
def _check_mandatory_policy(
self,
policy: GovernancePolicy,
feature: FeatureArtifact
) -> PolicyCheck:
"""Verify all mandatory requirements"""
check = PolicyCheck(policy_name=policy.name)
# Check required artifacts
missing_artifacts = []
for artifact_type in policy.required_artifacts:
if not self._has_artifact(feature, artifact_type):
missing_artifacts.append(artifact_type.value)
if missing_artifacts:
check.add_error(f"Missing required artifacts: {missing_artifacts}")
# Check required approvals
approval_check = self._validate_approvals(policy, feature)
check.merge(approval_check)
# Check tenure requirements
if policy.min_tenure_days:
tenure = (datetime.utcnow() - feature.stage_effective_date).days
if tenure < policy.min_tenure_days:
check.add_error(
f"Minimum tenure not met: {tenure}/{policy.min_tenure_days} days"
)
# Run custom validators
for validator in policy.custom_validators:
try:
validator_func = self._get_validator_function(validator)
validator_result = validator_func(feature, policy)
if not validator_result.is_valid:
check.add_errors(validator_result.errors)
except Exception as e:
check.add_error(f"Validator error: {str(e)}")
return check
Approval Workflow System
class ApprovalWorkflow:
"""Manages multi-stage approval processes"""
APPROVAL_MATRIX = {
LifecycleStage.INCEPTION: [
(Role.PRODUCT_MANAGER, 1),
(Role.TECHNICAL_LEAD, 1),
(Role.COMITTEE_CHAIR, 1) # for high-risk
],
LifecycleStage.GENERAL_AVAILABILITY: [
(Role.PRODUCT_MANAGER, 1),
(Role.ENGINEERING_DIRECTOR, 1),
(Role.SECURITY_OFFICER, 1),
(Role.COMPLIANCE_OFFICER, 1)
],
LifecycleStage.DEPRECATION_ANNOUNCED: [
(Role.PRODUCT_MANAGER, 1),
(Role.CUSTOMER_SUCCESS_LEAD, 1),
(Role.SUPPORT_LEAD, 1)
]
}
def create_approval_request(
self,
feature_id: UUID4,
target_stage: LifecycleStage,
requested_by: UserReference
) -> ApprovalRequest:
"""Create structured approval request"""
feature = self._get_feature(feature_id)
required_approvals = self.APPROVAL_MATRIX.get(target_stage, [])
request = ApprovalRequest(
feature_id=feature_id,
target_stage=target_stage,
requested_by=requested_by,
requested_at=datetime.utcnow(),
required_approvals=[
ApprovalRequirement(role=role, min_count=count)
for role, count in required_approvals
],
status=ApprovalStatus.PENDING
)
# Auto-assign approvers based on org structure
request.assigned_approvers = self._assign_approvers(
target_stage,
feature.stakeholders
)
# Notify approvers
self._notify_approvers(request)
return request
def record_approval(
self,
request_id: UUID4,
approver: UserReference,
decision: ApprovalDecision,
comments: Optional[str] = None
) -> ApprovalRecord:
"""Record individual approval decision"""
request = self._get_approval_request(request_id)
# Validate approver authority
if not self._can_approve(approver, request.required_approvals):
raise PermissionError("User not authorized for this approval")
record = ApprovalRecord(
request_id=request_id,
approver=approver,
decision=decision,
decided_at=datetime.utcnow(),
comments=comments,
role=self._get_approver_role(approver, request.target_stage)
)
# Check if request is now complete
if self._is_fully_approved(request):
request.status = ApprovalStatus.APPROVED
request.completed_at = datetime.utcnow()
# Auto-trigger transition
self.lifecycle_engine.transition(
feature_id=request.feature_id,
target_stage=request.target_stage,
initiated_by=request.requested_by,
approvals=self._get_approvals_for_request(request_id)
)
return record
Artifact Registry & Dependency Management
class ArtifactRegistry:
"""Centralized registry for all feature artifacts"""
def __init__(self):
self._graph = nx.DiGraph() # dependency graph
self._metadata_store = {}
def register_artifact(self, artifact: FeatureArtifact):
"""Register new feature with dependencies"""
# Store artifact metadata
self._metadata_store[artifact.id] = artifact
# Update dependency graph
self._graph.add_node(
artifact.id,
stage=artifact.current_stage,
risk=artifact.risk_level,
taxonomy=artifact.taxonomy
)
for dep_id in artifact.dependencies:
if dep_id in self._metadata_store:
self._graph.add_edge(artifact.id, dep_id)
# Validate dependency health
self._validate_dependency_chain(artifact.id)
def get_dependency_impact(
self,
artifact_id: UUID4,
analysis_type: ImpactAnalysis = ImpactAnalysis.DIRECT
) -> DependencyImpactReport:
"""Calculate impact of changes to this artifact"""
if analysis_type == ImpactAnalysis.DIRECT:
# Direct downstream dependents
dependents = list(self._graph.successors(artifact_id))
elif analysis_type == ImpactAnalysis.TRANSITIVE:
# All downstream
dependents = nx.descendants(self._graph, artifact_id)
elif analysis_type == ImpactAnalysis.CRITICAL_PATH:
# Features on critical path to GA
dependents = self._find_critical_path_dependents(artifact_id)
impact = DependencyImpactReport(
artifact_id=artifact_id,
dependent_count=len(dependents),
high_risk_dependents=[
d for d in dependents
if self._metadata_store[d].risk_level in [RiskLevel.HIGH, RiskLevel.CRITICAL]
],
stage_distribution=self._analyze_stage_distribution(dependents),
recommendations=self._generate_recommendations(dependents)
)
return impact
def _validate_dependency_chain(self, root_id: UUID4):
"""Check for cycles and invalid dependencies"""
# Check for cycles
try:
cycles = list(nx.simple_cycles(self._graph.subgraph(
nx.descendants(self._graph, root_id) | {root_id}
)))
if cycles:
raise DependencyCycleError(f"Cycles detected: {cycles}")
except nx.NetworkXNoCycle:
pass
# Check stage constraints (e.g., can't depend on sunset features)
for node in self._graph.nodes:
stage = self._metadata_store[node].current_stage
if stage in [LifecycleStage.DEPRECATION_IN_PROGRESS, LifecycleStage.SUNSET]:
# Check if any dependent is in GA or limited
for dependent in self._graph.predecessors(node):
dep_stage = self._metadata_store[dependent].current_stage
if dep_stage in [
LifecycleStage.GENERAL_AVAILABILITY,
LifecycleStage.LIMITED_AVAILABILITY
]:
self._log_dependency_warning(dependent, node)
Compliance & Audit System
class ComplianceAuditor:
"""Ensures regulatory and policy compliance"""
COMPLIANCE_FRAMEWORKS = {
ComplianceFramework.SOC2: ["access_logs", "change_management"],
ComplianceFramework.GDPR: ["data_processing", "consent_management"],
ComplianceFramework.HIPAA: ["phi_handling", "audit_trails"],
ComplianceFramework.ISO27001: ["risk_assessment", "security_controls"]
}
def generate_compliance_report(
self,
feature_id: UUID4,
framework: ComplianceFramework,
as_of_date: datetime = None
) -> ComplianceReport:
"""Generate compliance report for specific framework"""
feature = self._get_feature(feature_id)
requirements = self.COMPLIANCE_FRAMEWORKS[framework]
report = ComplianceReport(
feature_id=feature_id,
framework=framework,
generated_at=datetime.utcnow(),
as_of_date=as_of_date or datetime.utcnow(),
compliance_status=ComplianceStatus.UNKNOWN
)
for req in requirements:
check = self._check_compliance_requirement(
feature, req, as_of_date
)
report.add_check(req, check)
# Determine overall status
if all(c.status == ComplianceStatus.COMPLIANT for c in report.checks):
report.compliance_status = ComplianceStatus.COMPLIANT
elif any(c.status == ComplianceStatus.NON_COMPLIANT for c in report.checks):
report.compliance_status = ComplianceStatus.NON_COMPLIANT
else:
report.compliance_status = ComplianceStatus.PARTIAL
return report
def _check_compliance_requirement(
self,
feature: FeatureArtifact,
requirement: str,
as_of_date: datetime
) -> ComplianceCheck:
"""Check specific compliance requirement"""
check = ComplianceCheck(requirement=requirement)
# Check audit trail completeness
if requirement == "audit_trails":
relevant_transitions = [
t for t in feature.stage_history
if t.transition_date <= as_of_date
]
check.is_compliant = len(relevant_transitions) > 0
check.evidence = [t.id for t in relevant_transitions]
# Check for required approvals
elif requirement == "change_management":
critical_transitions = [
t for t in feature.stage_history
if t.to_stage in [
LifecycleStage.GENERAL_AVAILABILITY,
LifecycleStage.DEPRECATION_ANNOUNCED
] and t.transition_date <= as_of_date
]
all_approved = all(
any(a.decision == ApprovalDecision.APPROVED for a in t.approvals)
for t in critical_transitions
)
check.is_compliant = all_approved
check.evidence = [t.id for t in critical_transitions]
# Check data handling (example)
elif requirement == "data_processing":
check.is_compliant = feature.compliance_flags \
.intersection({ComplianceFramework.GDPR, ComplianceFramework.CCPA}) \
== set()
check.notes = "Manual review required for PII handling"
return check
API Endpoints (REST)
# Feature Management
POST /api/v1/features # Create new feature
GET /api/v1/features/{id} # Get feature details
PATCH /api/v1/features/{id} # Update metadata
DELETE /api/v1/features/{id} # Archive feature
# Lifecycle Operations
POST /api/v1/features/{id}/transitions # Request stage transition
GET /api/v1/features/{id}/transitions # Get transition history
GET /api/v1/features/{id}/timeline # Full lifecycle timeline
# Governance
GET /api/v1/policies # List governance policies
POST /api/v1/policies # Create new policy
GET /api/v1/features/{id}/validation # Validate against policies
GET /api/v1/features/{id}/compliance # Get compliance status
# Approvals
POST /api/v1/approvals/{request_id}/approve
POST /api/v1/approvals/{request_id}/reject
GET /api/v1/approvals/{request_id} # Get approval status
# Reports & Analytics
GET /api/v1/reports/lifecycle-metrics # Stage distribution, SLA metrics
GET /api/v1/reports/dependency-analysis?feature_id={id}
GET /api/v1/reports/compliance?framework=soc2&as_of=2024-01-01
# Admin Operations
POST /api/v1/admin/force-transition # Admin override (audited)
POST /api/v1/admin/renew-policy # Renew/update governance policy
GET /api/v1/admin/audit-log # Immutable audit trail
Event-Driven Architecture
class LifecycleEvents:
"""Event types emitted by the engine"""
EVENT_TYPES = {
"feature.created": {
"required_handlers": ["metadata_indexer", "notification_service"],
"payload_schema": FeatureCreatedEvent
},
"stage.transition.requested": {
"required_handlers": ["approval_service", "slack_notifier"],
"payload_schema": TransitionRequestedEvent
},
"stage.transition.completed": {
"required_handlers": ["compliance_service", "dashboard_updater"],
"payload_schema": TransitionCompletedEvent
},
"approval.required": {
"required_handlers": ["email_service", "task_creator"],
"payload_schema": ApprovalRequiredEvent
},
"compliance.violation": {
"required_handlers": ["alert_service", "ticket_creator"],
"payload_schema": ComplianceViolationEvent
},
"sunset.reminder": {
"required_handlers": ["notification_service"],
"payload_schema": SunsetReminderEvent
}
}
def emit(self, event_type: str, payload: dict, metadata: dict = None):
"""Publish event to message bus"""
if event_type not in self.EVENT_TYPES:
raise ValueError(f"Unknown event type: {event_type}")
event = {
"id": str(uuid4()),
"type": event_type,
"timestamp": datetime.utcnow().isoformat(),
"payload": payload,
"metadata": metadata or {}
}
# Validate against schema
schema = self.EVENT_TYPES[event_type]["payload_schema"]
validate(instance=payload, schema=schema)
# Publish to message bus (Kafka, RabbitMQ, etc.)
self.message_bus.publish(
topic=f"lifecycle.{event_type}",
message=json.dumps(event)
)
# Trigger required handlers synchronously/async
for handler in self.EVENT_TYPES[event_type]["required_handlers"]:
self._execute_handler(handler, event)
Deployment & Monitoring
# docker-compose.yml excerpt
services:
lifecycle-engine:
image: lifecycle-engine:latest
environment:
- DATABASE_URL=postgresql://...
- REDIS_URL=redis://...
- MESSAGE_BUS=kafka://...
- PROMETHEUS_METRICS=true
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
approval-service:
depends_on: [lifecycle-engine]
compliance-auditor:
schedule: "0 2 * * *" # Daily compliance checks
resources:
memory: "2Gi"
dashboard:
image: lifecycle-dashboard:latest
ports: ["3000:3000"]
Key Features
- State Machine Enforcement: Strict transition rules prevent invalid state jumps
- Policy-as-Code: Governance rules versioned and testable
- Immutable Audit Trail: Every change cryptographically signed
- Compliance Frameworks: SOC2, GDPR, HIPAA, ISO27001 out-of-box
- Dependency Impact Analysis: Understand ripple effects
- SLA Monitoring: Track approval times, documentation completeness
- Risk-Based Approvals: Different approval chains based on risk level
- Automated Reminders: Sunset notifications, renewal alerts
- Rollback Guarantees: Every transition has rollback plan validation
- Multi-Tenant: Isolate by organization/product line
Example Usage
# 1. Create a new feature
feature = engine.create_feature(
name="New Checkout Flow",
description="Redesigned checkout with 3 steps",
owner=user_jane,
taxonomy=Taxonomy.E_COMMERCE,
risk_level=RiskLevel.MEDIUM,
dependencies=[existing_payment_feature_id]
)
# 2. Request GA transition (triggers approval workflow)
approval_request = engine.request_transition(
feature_id=feature.id,
target_stage=LifecycleStage.GENERAL_AVAILABILITY,
requested_by=user_jane
)
# 3. Approvers get notified, review documentation
# 4. All approvals complete → automatic transition
# 5. Compliance reports generated automatically
# 6. Sunset date set (e.g., 2 years from GA)
This engine provides:
- Complete traceability from inception to sunset
- Automated governance with human-in-the-loop for high-risk
- Compliance-ready for audits
- Proactive alerts for renewal, sunset, SLA breaches
- Impact analysis for change planning
Would you like me to elaborate on any specific component, such as the policy definition language, the dependency resolution algorithm, or the compliance report generation?