Build a feature-flag dead code sweeper: coverage, timeouts, and owner nudges.
- User
Build a feature-flag dead code sweeper: coverage, timeouts, and owner nudges.
- Assistant
Build a feature-flag dead code sweeper: coverage, timeouts, and owner nudges.
We are going to build a system that:
Steps: a) We need to define a feature flag registry. This could be a database or a configuration file, but for the sake of this example, we'll assume we have a way to query active flags. b) We need to instrument the code to track when a feature flag is used (for coverage). c) We need a way to set and track expiration times for flags. d) We need to define owners for each flag (could be a team or an individual email). e) We need a sweeper that periodically: - Checks for flags that have expired but are still in the code (dead code) and not used recently (coverage low or zero). - Sends notifications to owners about flags that are about to expire and those that have expired but are still present.
Implementation:
Feature Flag Registry: Let's assume we have a global feature flag service (like LaunchDarkly, or a custom one). We need to extend it to store:
Instrumentation: We can wrap the feature flag check function. For example, in Python:
Original: if feature_flags.is_enabled('new_feature'): ... new feature code ...
Instrumented: if feature_flags.is_enabled_and_track('new_feature'): ... new feature code ...
The is_enabled_and_track would:
- Check if the flag is enabled.
- If enabled, record the usage (update last_used timestamp for that flag).
Alternatively, we can have a decorator or context manager.
Expiration: We can set a default expiration (e.g., 90 days) when a flag is created, but allow overriding. We can have a cron job that runs daily to: - Find flags that are expired (expiration date < today) and have not been used in the last X days (or never used) and are still in the code (we need to know if they are still in the codebase).
Dead Code Detection: This is the tricky part. We need to know if the flag is still present in the codebase. We can do: - Static analysis: scan the codebase for the flag name. But note that the flag string might be built dynamically. - Alternatively, we can rely on the fact that if the flag is not used (coverage zero) and expired, then it's dead code. But what if the flag is used in a branch that is not covered by our tests? We might have false positives.
We can combine: - Coverage: if the flag has been used (last_used is recent) then we assume it's alive. - Static analysis: we can have a list of flags that are still referenced in the code (by string matching) and then check against that.
However, note that feature flags might be used in multiple repositories. We might need a more distributed approach.
Owner Nudges: We can send emails or messages (Slack, etc.) to the owners: - Warning: flag will expire in 7 days and has low coverage (or zero). - Expired: flag has expired and is still in the code (and possibly low coverage).
Sweeper Process:
Steps for the sweeper (daily run):
For each flag in the registry: a) Check if the flag is expired (expiration_date < today). b) Check the last_used date. If never used or last_used is older than, say, 30 days (or a threshold) then: - Check if the flag is still present in the codebase (static analysis). If not present, then we can remove it from the registry and maybe clean up the code (but code cleanup might be a separate process). - If present, then it's dead code and we notify the owner.
c) For flags that are about to expire (expiration_date in the next 7 days) and have low coverage, we can send a warning.
However, note that we might not want to remove a flag just because it's expired and dead. We might want to give the owner a chance to renew or remove the code. So maybe:
- Expired and dead code: notify and then after a grace period (e.g., 7 days) remove from registry and maybe open a pull request to remove the code? (That's more advanced.)
Let's break down the states:
Active: not expired, or expired but renewed (we can have a renewal process).
Expired: past expiration date.
Dead: expired and not used (or not present in code).
We can have:
- If expired and last_used is recent (within 30 days) then we consider it still active (maybe the owner forgot to renew) -> we can send a renewal nudge.
- If expired and last_used is old (or never) then we check code presence:
- If not present: we can remove from registry (no action needed for code because it's already gone?).
- If present: dead code, we notify and then after grace period, we can automatically remove from registry and maybe create a ticket to remove the code.
Implementation Plan:
We need:
a) A way to store flag metadata (registry). We can use a database table:
Table: feature_flags
Columns:
id (primary key)
name (unique)
created_at
expiration_date
owner (email or team)
last_used (nullable, datetime)
b) Instrumentation code that updates last_used when the flag is checked and enabled.
c) A sweeper script that:
Static Analysis:
We need to search the codebase for the flag name. But note: the flag might be used as a string literal or as a variable. We are looking for the string that is the flag name.
We can have a list of codebases (or directories) to search. We can run:
grep -r "flag_name" /path/to/codebase
But this might match in comments, logs, etc. We can try to look for the specific pattern of how we check the flag.
For example, in our instrumentation, we have:
if feature_flags.is_enabled_and_track('new_feature'):
So we are looking for the string 'new_feature' in the code. But it might be in a variable assignment:
flag = 'new_feature'
if feature_flags.is_enabled(flag):
Then our grep might not find it if we only look for 'new_feature' as a string in the condition? Actually, we would find it in the assignment.
But note: the flag name might be built dynamically:
flag = 'new_' + 'feature'
Then we won't find it.
Given the difficulty, we might rely on:
- The instrumentation: if the flag is checked (enabled or disabled) then we record it. So if the flag is never checked, then we don't have any record. But then we don't know if the flag is still in the code.
Alternative: we can have a build step that extracts all flag names from the code (by static analysis) and then we compare with the registry.
We can do:
- At build time, we run a script that extracts all string literals that are passed to `feature_flags.is_enabled` (or similar) and also any variable that is used as the argument? That's hard.
Given the complexity, let's assume we have a limited set of codebases and we can do a simple grep for the flag name. We'll accept some false positives (flags that appear in comments) and false negatives (dynamic flags).
Putting it together:
We'll create:
- A database (or a simple JSON file for small scale) to store flag metadata.
- An instrumentation library that updates the last_used (and last_checked) for a flag.
- A sweeper script that runs daily and:
a) Queries the database for flags that are expired or about to expire.
b) For each flag, check the last_used and last_checked (if we record checks) to decide the state.
c) Run static analysis (grep) on the codebase to see if the flag string appears.
d) Send notifications.
We can also have a renewal process: if the owner wants to keep the flag, they can renew the expiration date.
Example code structure:
feature_flag_registry.py (the instrumentation)
class FeatureFlagRegistry: def init(self, db_connection): self.db = db_connection
def is_enabled(self, flag_name):
# check if the flag is enabled (from config or remote)
# then update the last_used if enabled? Or update on every check?
# Let's update on every check (for coverage of the check itself) and also if enabled, we update last_enabled?
# We'll record:
# last_checked: every time we check the flag.
# last_enabled: only when the flag is enabled.
# First, update last_checked for the flag.
self._update_last_checked(flag_name)
enabled = ... # get the current value of the flag
if enabled:
self._update_last_enabled(flag_name)
return enabled
def _update_last_checked(self, flag_name):
# update the last_checked timestamp for the flag in the database.
pass
def _update_last_enabled(self, flag_name):
# update the last_enabled timestamp for the flag in the database.
pass
sweeper.py
import subprocess from datetime import datetime, timedelta
def run_sweeper(): # 1. Get all flags from registry that are expired or about to expire. flags = get_flags()
Challenges:
We can also have a way for developers to mark a flag as "removed" when they remove the code, so we don't have to rely on static analysis.
Alternatively, we can have a process:
Given the trade-offs, we might start with:
But then we might have flags that are expired and not used but the code is still there (dead code). We want to catch that.
We can do:
Step 1: Notify for expired flags that have low usage. Step 2: After 7 days, if the flag is still in the registry and expired and low usage, then we can automatically remove the flag from the registry (but not the code). Then we can open a ticket for the owner to remove the code.
Without static analysis, we don't know if the code is there. So we might remove a flag that is still in the code? That's dangerous because the code might break.
So we must check code presence before removing the flag from the registry? Or we can remove the flag from the registry and then if the code is still there, it will break because the flag is not found? That's bad.
Therefore, we should not remove the flag from the registry until we are sure the code is gone. Or we can remove the flag from the registry only after we have removed the code.
So the process:
Or we can have a manual step: the owner must confirm that the code is removed, then we remove the flag.
Given the complexity, let's change the goal:
We are building a "dead code sweeper" for feature flags. We want to:
- Identify feature flags that are expired and have not been used (enabled) in the last 90 days and are still present in the code.
Then we report them. We don't automatically remove. We just report.
Let's adjust the sweeper to only report.
Also, we need to consider:
We can combine with code coverage data? That's another level.
Given the scope, we'll stick to:
- Flag is considered "used" if it has been enabled in the last 90 days.
And we assume that if the flag is enabled, then the code under it is at least partially executed (because the condition is true). But note: the code under the flag might be in a branch that is not taken even if the flag is true. We'll ignore that.
Final plan:
a) Create a registry (database) for feature flags with: - name - created_at - expiration_date - owner - last_enabled (nullable)
b) Instrument the feature flag check to update last_enabled when the flag is enabled.
c) Run a sweeper that:
For each flag in the registry:
if expiration_date < today:
if last_enabled is null or (today - last_enabled) > 90 days:
if flag string is found in the codebase (static analysis):
report dead flag (with owner, name, expiration, last_enabled)
else:
# flag not in code, we can remove from registry? But we don't know if it's in other codebases? We only searched the ones we know.
# We can remove if we are sure it's not in any codebase we care about.
# Or we can leave it and wait for the owner to remove?
pass
if expiration_date is in the next 7 days and (last_enabled is null or (today - last_enabled) > 90 days):
send warning to owner.
d) The report can be an email or a dashboard.
Implementation details for static analysis:
We'll have a list of codebase paths (maybe from a config file). We'll search in these paths for the flag name as a string.
We can improve by looking for the specific pattern of the feature flag check, but for simplicity we'll just search for the flag name.
We must be cautious: the flag name might be a substring of another flag or variable. We can search for the exact string in quotes? But the flag might be used without quotes.
We can do:
grep -r -w "flag_name" ...
But that will only match whole words. And if the flag is used in a string without spaces? We can use:
grep -r -E "(^|[^a-zA-Z0-9_])flag_name([^a-zA-Z0-9_]|$)" ...
But that's complex.
Alternatively, we can search for the flag name as a string in the code and then filter by the context? Not in this first version.
We'll do:
grep -r -F "flag_name" ...
This will match the exact string. But note: if the flag name is "new_feature", then it will match "new_feature" and also "my_new_feature_flag". So we might get false positives.
We can try to match with word boundaries in Python's regex, but in grep we can use -w (word regexp) but that uses [a-zA-Z0-9_]. So if the flag name has other characters, it might not work.
Given the trade-off, we'll use:
grep -r -F "flag_name" ...
And accept that we might have false positives. Then the report might include flags that are not actually used (but appear in comments). We can have a manual verification step.
Let's code the sweeper in Python, assuming we have a database and a way to get the flags.
We'll also need a way to configure the codebases to search.
We'll assume the registry is in a PostgreSQL database.
Example:
Table: feature_flags id SERIAL PRIMARY KEY, name VARCHAR(255) UNIQUE NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW(), expiration_date DATE NOT NULL, owner VARCHAR(255) NOT NULL, last_enabled TIMESTAMP
We'll write the sweeper as a standalone script that can be run by cron.
We'll also need to handle the instrumentation. We can have a library that the applications import and use.
Given the complexity and the fact that we are only designing, we'll write the sweeper and the instrumentation in a simplified manner.
Let's write the code for the sweeper:
sweeper.py:
import psycopg2 from datetime import datetime, timedelta import subprocess import configparser
config = configparser.ConfigParser() config.read('sweeper_config.ini')
DB_CONN_STRING = config['database']['conn_string'] CODEBASES = config['codebases']['paths'].split(',')
def get_expired_flags(): conn = psycopg2.connect(DB_CONN_STRING) cur = conn.cursor() cur.execute(""" SELECT name, owner, expiration_date, last_enabled FROM feature_flags WHERE expiration_date < %s """, (datetime.now().date(),)) flags = cur.fetchall() cur.close() conn.close() return flags
def get_flags_about_to_expire(): conn = psycopg2.connect(DB_CONN_STRING) cur = conn.cursor() cur.execute(""" SELECT name, owner, expiration_date, last_enabled FROM feature_flags WHERE expiration_date >= %s AND expiration_date < %s """, (datetime.now().date(), datetime.now().date() + timedelta(days=7))) flags = cur.fetchall() cur.close() conn.close() return flags
def is_flag_in_code(flag_name): for codebase in CODEBASES: cmd = f"grep -r -F '{flag_name}' {codebase}" result = subprocess.run(cmd, shell=True, capture_output=True, text=True) if result.returncode == 0: return True return False
def send_dead_code_notification(owner, flag_name, expiration_date, last_enabled): # Implement email or Slack notification print(f"Dead code: flag {flag_name} expired on {expiration_date}, last enabled: {last_enabled}. Owner: {owner}")
def send_expiring_soon_notification(owner, flag_name, expiration_date, last_enabled): print(f"Flag {flag_name} will expire on {expiration_date}, last enabled: {last_enabled}. Owner: {owner}")
def main(): # Check expired flags expired_flags = get_expired_flags() for flag in expired_flags: name, owner, expiration_date, last_enabled = flag # Check if last_enabled is older than 90 days or null if last_enabled is None or (datetime.now() - last_enabled) > timedelta(days=90): if is_flag_in_code(name): send_dead_code_notification(owner, name, expiration_date, last_enabled)
# Check flags about to expire
about_to_expire = get_flags_about_to_expire()
for flag in about_to_expire:
name, owner, expiration_date, last_enabled = flag
if last_enabled is None or (datetime.now() - last_enabled) > timedelta(days=90):
send_expiring_soon_notification(owner, name, expiration_date, last_enabled)
if name == 'main': main()
The instrumentation:
feature_flag.py:
import psycopg2 from datetime import datetime
DB_CONN_STRING = ... # from config
class FeatureFlagRegistry: def init(self): self.conn = psycopg2.connect(DB_CONN_STRING)
def is_enabled(self, flag_name):
# First, update last_checked? We don't have that in our table. We only have last_enabled.
# We are only updating last_enabled when the flag is enabled.
# But we also want to know if the flag is checked? We don't record that.
# Get the flag value (from where? We might have a separate table for flag values? Or we store the value in the same table?)
# Let's assume we have a table feature_flag_values that maps flag_name to a boolean.
cur = self.conn.cursor()
cur.execute("SELECT value FROM feature_flag_values WHERE name = %s", (flag_name,))
row = cur.fetchone()
if row is None:
# Flag doesn't exist? Maybe default to False?
enabled = False
else:
enabled = row[0]
if enabled:
cur.execute("""
UPDATE feature_flags
SET last_enabled = %s
WHERE name = %s
""", (datetime.now(), flag_name))
self.conn.commit()
cur.close()
return enabled
def close(self):
self.conn.close()
Then in the application:
feature_flags = FeatureFlagRegistry()
if feature_flags.is_enabled('new_feature'):
# do new feature
We must ensure that we close the connection when the app shuts down.
But note: we are updating the database on every flag check that is enabled. That might be a performance issue. We can batch updates? Or we can update only once per minute? But then we lose precision.
Alternatively, we can have a separate process that aggregates the checks (like a logging system) and then updates the registry. But that's more complex.
We'll do the simple approach: update on every enabled check.
We also need to create the tables:
CREATE TABLE feature_flags ( id SERIAL PRIMARY KEY, name VARCHAR(255) UNIQUE NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW(), expiration_date DATE NOT NULL, owner VARCHAR(255) NOT NULL, last_enabled TIMESTAMP );
CREATE TABLE feature_flag_values ( flag_name VARCHAR(255) PRIMARY KEY, value BOOLEAN NOT NULL );
And we need to set the expiration_date when we create a flag. We can have a default of 90 days from creation.
We also need a way to create flags. We can have a management command or an admin interface.
Given the time, we'll assume we have a way to create flags with an owner and expiration.
This is a basic design. There are many edge cases and optimizations.
Let's note:
The static analysis might be slow if we have many codebases and many flags. We can cache the results? But flags might be added/removed.
We are only searching for the exact string. If the flag name is a substring of another, we might get false positives.
We are not handling dynamic flag names.
We are only considering enabled usage. What about disabled? We might want to record every check? We don't have that in our current schema.
We can extend:
We'll update the instrumentation to also update last_checked on every check.
ALTER TABLE feature_flags ADD COLUMN last_checked TIMESTAMP;
In is_enabled:
update last_checked to now() every time.
Then in the sweeper, we can use last_checked to see if the flag is still being checked? But we are already doing static analysis.
We can use last_checked to skip static analysis if last_checked is very recent? Because if we checked it recently, it must be in the code. But note: the static analysis might not find it if it's in a different codebase. So we might have multiple codebases and we only search some.
Given the distributed systems, we might need to have each service report its own flags? That's a different architecture.
For now, we assume a monorepo or that we search all codebases.
Given the time, we'll stick to the original plan and only use last_enabled.
Let's adjust the sweeper condition to:
if expired and (last_enabled is null or (today - last_enabled) > 90 days) and is_flag_in_code(flag_name):
report
We'll also send warnings for flags about to expire (in 7 days) that meet the same condition (last_enabled is null or old).
This design is a starting point. We can refine as we learn more.
Let's write the code accordingly.
We'll also need to handle the case where the flag is not in the registry (maybe it was removed by another process). We handle that by checking if the flag exists in the registry.
We assume the registry is the source of truth.
We'll also need to consider timezones. We'll use UTC for everything.
Let's code accordingly.
Given the complexity and the fact that we are in a text-based environment, I'll write the code in a simplified manner.
We'll create:
We'll assume the database is PostgreSQL.
We'll also assume we have a way to set the flag values (maybe another table and a separate admin tool).
We'll not implement the admin tool.
Let's write the code.
Note: This is a simplified version for demonstration. In production, we would need error handling, logging, more efficient static analysis, etc. I'll design a comprehensive Feature Flag Dead Code Sweeper that systematically identifies, tracks, and helps eliminate unused or expired feature flags. This system combines coverage analysis, timeout enforcement, and owner nudges.
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Codebase │ │ Feature Flag │ │ Registry & │
│ (with flags) │───▶│ Instrumentation│───▶│ Metadata DB │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Coverage │◀───│ Sweeper │───▶│ Notification │
│ Analysis │ │ Engine │ │ System │
└─────────────────┘ └──────────────────┘ └─────────────────┘
CREATE TABLE feature_flags (
id UUID PRIMARY KEY,
name VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
created_by VARCHAR(255) NOT NULL,
owner_email VARCHAR(255) NOT NULL,
team VARCHAR(100),
description TEXT,
expiration_date DATE NOT NULL,
renewal_count INT DEFAULT 0,
last_renewed TIMESTAMP,
status VARCHAR(50) DEFAULT 'active', -- active, expired, deprecated, removed
tags JSONB,
metadata JSONB
);
CREATE TABLE flag_usage (
id UUID PRIMARY KEY,
flag_id UUID REFERENCES feature_flags(id),
timestamp TIMESTAMP NOT NULL,
environment VARCHAR(50), -- prod, staging, dev
service_name VARCHAR(255),
user_id_hash VARCHAR(255), -- hashed for privacy
was_enabled BOOLEAN,
UNIQUE(flag_id, timestamp, environment, service_name)
);
CREATE TABLE flag_coverage (
flag_id UUID REFERENCES feature_flags(id),
environment VARCHAR(50),
last_used TIMESTAMP,
total_requests INT DEFAULT 0,
enabled_requests INT DEFAULT 0,
unique_users INT DEFAULT 0,
PRIMARY KEY (flag_id, environment)
);
# feature_flag_client.py
import uuid
from datetime import datetime
from typing import Optional
class FeatureFlagClient:
def __init__(self, flag_name: str, registry_url: str):
self.flag_name = flag_name
self.registry_url = registry_url
self.flag_id = self._lookup_flag_id()
def is_enabled(self,
user_id: Optional[str] = None,
environment: str = "prod",
service_name: str = "unknown") -> bool:
"""Check flag with automatic usage tracking"""
# 1. Get flag value from flag provider (LaunchDarkly, Flagsmith, etc.)
enabled = self._get_flag_value()
# 2. Track usage asynchronously (non-blocking)
self._track_usage(
user_id=user_id,
environment=environment,
service_name=service_name,
was_enabled=enabled
)
return enabled
def _track_usage(self, user_id, environment, service_name, was_enabled):
"""Async usage tracking"""
# Send to message queue (Kafka/RabbitMQ) for processing
usage_data = {
"flag_id": self.flag_id,
"timestamp": datetime.utcnow().isoformat(),
"environment": environment,
"service_name": service_name,
"user_id_hash": self._hash_user_id(user_id),
"was_enabled": was_enabled
}
# publish to kafka topic 'flag-usage'
pass
# notification_system.py
class NotificationSystem:
def __init__(self, smtp_config, slack_webhook, teams_webhook):
self.smtp = smtp_config
self.slack = slack_webhook
self.teams = teams_webhook
def send_nudge(self, action: Dict):
"""Send appropriate nudge based on severity and channel preferences"""
owner = action['owner']
team = self._get_team_preferences(owner)
if action['priority'] == 'high':
# Send urgent notifications across all channels
self._send_email(
to=owner,
subject=f"🚨 URGENT: Dead Feature Flag - {action['flag_name']}",
template='dead_flag_urgent.html',
data=action
)
self._send_slack_alert(action, channel=f"#{team}-alerts")
self._create_teams_card(action)
elif action['priority'] == 'medium':
# Send weekly digest + Slack
self._add_to_weekly_digest(action)
self._send_slack_message(action, channel=f"#{team}-flags")
def _generate_escalation_policy(self, days_overdue: int):
"""Escalate if no response"""
if days_overdue > 7:
return 'escalate_to_tech_lead'
elif days_overdue > 14:
return 'escalate_to_manager'
elif days_overdue > 30:
return 'escalate_to_director'
return None
<!-- dead_flag_urgent.html -->
<h2>Dead Feature Flag Detected: {{ flag_name }}</h2>
<p>Feature flag <strong>{{ flag_name }}</strong> has been expired for
<strong>{{ days_since_last_use }} days</strong> with no usage.</p>
<h3>Actions Required:</h3>
<ol>
<li><strong>Remove dead code</strong>: Search your codebase for "{{ flag_name }}"</li>
<li><strong>Delete the flag</strong>: From your flag management system</li>
<li><strong>Verify removal</strong>: Ensure no references remain</li>
</ol>
<p>Or if the feature is still needed, <a href="{{ renewal_url }}">renew the flag</a>
with a new expiration date.</p>
{% if ticket_url %}
<p>Ticket created: <a href="{{ ticket_url }}">{{ ticket_url }}</a></p>
{% endif %}
<p>This is an automated sweep. Contact infra-team@example.com with questions.</p>
# coverage_analyzer.py
class CoverageAnalyzer:
def __init__(self, kafka_consumer, db):
self.consumer = kafka_consumer # Consumes from 'flag-usage' topic
self.db = db
def process_usage(self):
"""Process flag usage events in real-time"""
for message in self.consumer:
usage = json.loads(message.value)
# Update coverage metrics
self._update_coverage_metrics(
flag_id=usage['flag_id'],
environment=usage['environment'],
timestamp=usage['timestamp']
)
# Check for sudden drops (flag might be broken)
self._detect_sudden_drop(usage['flag_id'])
def _detect_sudden_drop(self, flag_id: str):
"""Alert if flag usage suddenly stops (could indicate bug)"""
recent_usage = self._get_recent_usage(flag_id, hours=24)
historical_avg = self._get_historical_average(flag_id, days=30)
if (recent_usage['request_count'] < historical_avg * 0.1 and
historical_avg > 100): # Only if previously active
self._create_incident(
f"Feature flag {flag_id} usage dropped 90%",
severity="warning"
)
thresholds:
coverage_days: 90
expiration_warning_days: 30
grace_period_days: 14
min_requests_for_activity: 100
notification:
channels:
- email
- slack
- teams
escalation:
days_until_escalation: [7, 14, 30]
coverage:
environments: ["prod", "staging"]
exclude_services: ["monitoring", "cron-jobs"]
include_patterns: ["main", "api", "web"]
ticketing:
auto_create: true
project: "TECH_DEBT"
issue_type: "Task"
Flag Health Score:
health = (usage_score * 0.4 +
renewals_score * 0.3 +
owner_responsiveness * 0.3)
Dead Code Volume: Total lines of dead flag code
Owner Response Time: Average time to act on nudges
False Positive Rate: Flags marked dead but still needed
False Positives:
emergency_override tagProduction Impact:
Privacy:
# Daily cron at 2 AM
0 2 * * * /usr/bin/python /opt/sweeper/sweeper_engine.py
# Output:
# ✅ Sweep completed in 45s
# 🎯 Found 23 dead flags, 47 expiring soon
# 📧 Sent 42 nudges (15 urgent, 27 warnings)
# 🎫 Created 18 removal tickets
# 📊 Dead code volume: 12,450 lines
| System | Integration | Purpose |
|---|---|---|
| CI/CD | Pre-merge check | Block new flags without expiration dates |
| Git | Hook integration | Detect flag removal in PRs |
| Monitoring | Alert on sudden drops | Catch broken flags |
| Cost System | Track flag costs | Show $ impact of unused flags |
This system provides systematic elimination of dead feature flags through:
The key is automation without auto-destruction - the system identifies and nudges, but humans make final removal decisions, preventing production incidents from premature flag deletion.
Step 1: Get all flags that are expired (expiration_date < today) OR will expire in the next 7 days (for warnings).
Step 2: For each flag, check the last_used. If last_used is older than 30 days (or null) then:
- Run static analysis to see if the flag string appears in the codebase (or in a set of known codebases). We can have a list of codebases (or directories) to check.
How to do static analysis? We can use `grep` or a more sophisticated tool. But note: the flag might be used in a comment or in a string that is not a condition. We might have false positives.
Alternatively, we can rely on the fact that our instrumentation only records when the flag is checked (and enabled). So if the flag is never checked (and enabled) then it's dead. But what if the flag is checked but the condition is never true? Then we wouldn't record a usage. So we might miss dead flags that are always false.
We can adjust: if the flag is checked (even if false) we record that it was checked? But then we don't know if the code under the flag is executed. However, if the flag is always false, then the code under it is dead. But that's a different kind of dead code.
Let's clarify:
We are concerned about:
- Flags that are set to true but the code under them is never executed (so the flag is unnecessary).
- Flags that are set to false and the code under them is never executed (so the flag and the code are dead).
Our instrumentation records only when the flag is enabled. So if the flag is disabled, we don't record. That means:
- If a flag is disabled and the code under it is never executed (because the condition is false) then we have no usage. That's dead code.
- If a flag is enabled and the code under it is executed, we record usage.
- If a flag is enabled but the code under it is not executed (because the condition is true but the code path is not hit) then we record usage but the code under the flag might be dead? Actually, if the condition is true and the code is not executed, that's a bug in the code, not the flag. But note: the flag is being used (the condition is evaluated) so we record usage. So we might not catch that.
Given the complexity, maybe we should record every check (regardless of the value) and then also track if the code under the flag was executed? That would require more instrumentation (like tracing). Alternatively, we can use code coverage tools and combine with flag checks.
Given the scope, let's stick to:
- We record usage only when the flag is enabled and the code under it is executed? Actually, we can only record when the flag check happens and it's enabled. We don't know if the code under it runs.
But wait: if the flag is enabled and the condition is true, then the code under it will run (unless there's an exception or early return). So we can assume that if the flag is enabled, then the code under it is intended to run. However, if the code under the flag is in a branch that is not taken (due to other conditions) then we might not run it even if the flag is true.
This is getting too complex.
Let's simplify the goal: we want to remove feature flags that are no longer needed. A feature flag is no longer needed if:
- The code under the flag is permanently deployed and we can remove the flag and the conditional.
How do we know?
We can set a timeout (e.g., 90 days) and then check:
1. Has the flag been used (enabled) in the last 90 days? (This means the code under the flag has been executed at least once in the last 90 days.)
2. Is the flag still present in the code? (Static analysis.)
So we can do:
- If the flag is expired and last_used is older than 90 days (or never) and the flag string is still in the code, then it's a candidate for removal.
But note: the flag might be set to false and the code under it might be dead. We don't record usage when the flag is false. So if a flag is set to false and never set to true, then last_used is null. And if the code under the flag is dead (because the condition is false) then we want to remove the flag and the code.
So we need to record every check? Let's change the instrumentation:
We record:
- flag name
- timestamp
- whether it was enabled or not.
Then we can say: if the flag has been checked (enabled or disabled) in the last 90 days, then it's still active. But what if it's always disabled? Then the code under it is dead. So we might want to remove the flag and the code.
Alternatively, we can say: if the flag has been enabled in the last 90 days, then the code under it has been executed at least once. If it's never been enabled, then the code under it might be dead.
Given the complexity, let's define:
A flag is "active" if it has been enabled in the last 90 days.
A flag is "checked" if it has been checked (enabled or disabled) in the last 90 days.
Then:
- If a flag is expired and has not been enabled in the last 90 days, then we can consider removing it.
- But we also want to check if the flag is still in the code. If it's not in the code, then we remove it from the registry.
- If it's in the code, then we notify the owner.
However, if the flag is set to false and never enabled, but the code under it is actually needed for a future release (when the flag is turned on) then we don't want to remove it. But if it's expired, then the plan was to remove it by the expiration date. So if it's expired and not enabled recently, it's a candidate.
So:
Step for expired flags (expiration_date < today):
if last_enabled_date is more than 90 days ago (or null) then:
if flag is still in the codebase -> dead code, notify owner.
else -> remove from registry.
For flags about to expire (in 7 days):
if last_enabled_date is more than 90 days ago (or null) then send a warning: "This flag will expire and hasn't been enabled recently. Please remove the code or renew the flag."
We can also have a whitelist of files to search (only source files, not tests, etc.)
today = datetime.now()
for flag in flags:
expiration_date = flag.expiration_date
last_enabled = flag.last_enabled
# If expired
if expiration_date < today:
# Check if we have a recent enabled usage (last 90 days)
if last_enabled and (today - last_enabled) < timedelta(days=90):
# It's still active, maybe send a renewal reminder?
send_renewal_reminder(flag.owner, flag.name)
else:
# Check if the flag is still in the codebase
if is_flag_in_code(flag.name):
# Dead code, notify
send_dead_code_notification(flag.owner, flag.name, flag.expiration_date)
else:
# Flag not in code, remove from registry
remove_flag_from_registry(flag.name)
# If about to expire (in 7 days)
elif expiration_date - today < timedelta(days=7):
if last_enabled and (today - last_enabled) < timedelta(days=90):
# It's active, no warning? Or maybe we still want to remind about expiration?
pass
else:
send_expiring_soon_with_low_coverage(flag.owner, flag.name, flag.expiration_date)
def is_flag_in_code(flag_name): # Search in a set of codebases (list of directories) codebases = ['/path/to/repo1', '/path/to/repo2'] for codebase in codebases: # Use grep to search for the flag name as a string literal? We'll look for the flag name in single or double quotes? # We are looking for: 'flag_name' or "flag_name" # But note: the flag might be used without quotes if it's a variable? Then we can't find it.
# We'll do: grep -r --include=\*.py "flag_name" codebase
# But we must escape the flag_name for shell.
cmd = f"grep -r --include=\*.py '{flag_name}' {codebase}"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode == 0:
return True
return False
So the sweeper will:
For each expired flag:
if last_enabled is older than 90 days (or null):
if is_flag_in_code(flag_name):
report(flag_name, owner, expiration_date, last_enabled)
And for flags about to expire (in 7 days) and last_enabled older than 90 days, we send a warning.
We'll leave the removal to the owners.
ALTER TABLE feature_flags ADD COLUMN last_checked TIMESTAMP;
Then in `is_enabled` we update last_checked every time, and last_enabled only when enabled.
Then in the sweeper, we can use last_checked to see if the flag is still being checked? But if the flag is always disabled, then last_enabled is null but last_checked is recent. Then we know the flag is still in the code and being checked. But the code under the flag is dead because the flag is disabled. That's a different scenario.
We might want to remove flags that are always disabled? But the owner might plan to enable it in the future.
Given the expiration date, if the flag is expired and always disabled, then it's dead code.
So we can change:
For expired flags:
if last_enabled is null and last_checked is recent (within 90 days) then the flag is being checked but never enabled -> dead code (the code under the flag is never executed). So we report.
if last_checked is old (or null) then the flag is not even being checked -> probably dead code.
So we can use both last_enabled and last_checked.
Let's change the condition:
We want to report if:
- The flag is expired.
- And (last_enabled is null OR (last_enabled is old and last_checked is old?))
Actually, if the flag is checked (last_checked recent) but never enabled (last_enabled null) then the code under the flag is dead. So we report.
If the flag is not checked (last_checked old) then we report.
So:
if expired:
if (last_checked is null or (today - last_checked) > 90) or
(last_enabled is null and (today - last_checked) <= 90) # but then we have recent check but never enabled -> dead code
Actually, we can simplify: if the flag is expired and (last_enabled is null OR (today - last_enabled) > 90) then we report? But what if last_checked is recent and last_enabled is null? Then we want to report because the code under the flag is dead.
So condition: if expired and (last_enabled is null OR (today - last_enabled) > 90) then report? That would also report if last_enabled is old but last_checked is recent? That might be a flag that was enabled in the past but not recently, but still being checked. That might be a flag that is set to false now? Then the code under it is dead. So we want to report that too.
So:
if expired and (last_enabled is null OR (today - last_enabled) > 90):
# This means the flag has not been enabled in the last 90 days (or never). Then the code under the flag (if the flag is true) would not have been run in the last 90 days. But what if the flag is true and the code under it is run only when the flag is true? Then the code under the flag is dead.
But wait: what if the flag is true and the code under it is run only when the flag is true, but the flag was true 91 days ago and then turned off? Then the code under it hasn't run in 91 days. So it's dead.
And if the flag is false, then the code under it never runs. So if the flag has never been enabled, then the code under it is dead.
So the condition holds.
But we also need to check if the flag is still in the code.
So we don't need last_checked for the condition? We only need it to know if the flag is still being checked (so it's in the code). But we are doing static analysis for that.
Actually, we can use last_checked to avoid static analysis? If last_checked is recent, then the flag is definitely in the code (because we just checked it). But what if the flag was checked in a codebase that we don't search? Then static analysis might miss it.
Given the complexity, let's stick to:
Condition for report:
flag is expired AND (last_enabled is null OR (today - last_enabled) > 90) AND (flag is found in codebase via static analysis)
We'll ignore last_checked for now.
# sweeper_engine.py
from datetime import datetime, timedelta
from typing import List, Dict
import json
class DeadCodeSweeper:
def __init__(self, db_connection, flag_client, notifier):
self.db = db_connection
self.flag_client = flag_client
self.notifier = notifier
# Configurable thresholds
self.COVERAGE_THRESHOLD_DAYS = 90 # No usage = dead
self.EXPIRATION_WARNING_DAYS = 30
self.GRACE_PERIOD_DAYS = 14
def run_sweep(self):
"""Main sweep execution - run daily via cron"""
# 1. Find expired/expiring flags
expired_flags = self._get_expired_flags()
expiring_soon = self._get_flags_expiring_in_days(
self.EXPIRATION_WARNING_DAYS
)
# 2. Analyze coverage
dead_flags = self._analyze_coverage(expired_flags)
at_risk_flags = self._analyze_coverage(expiring_soon)
# 3. Generate actions
actions = self._generate_actions(dead_flags, at_risk_flags)
# 4. Execute actions (nudge owners, create tickets)
self._execute_actions(actions)
# 5. Update flag statuses
self._update_flag_statuses(dead_flags, "deprecated")
return actions
def _analyze_coverage(self, flags: List[Dict]) -> List[Dict]:
"""Check if flags have been used recently"""
dead = []
for flag in flags:
coverage = self._get_coverage_data(flag['id'])
if not coverage:
# Never used
flag['coverage_status'] = 'never_used'
flag['days_since_last_use'] = (datetime.now() -
flag['created_at']).days
else:
days_since = (datetime.now() - coverage['last_used']).days
flag['coverage_status'] = 'stale' if days_since > 90 else 'active'
flag['days_since_last_use'] = days_since
# Determine if dead
if (flag['status'] == 'expired' and
flag['coverage_status'] in ['never_used', 'stale']):
dead.append(flag)
return dead
def _generate_actions(self, dead_flags: List[Dict],
at_risk_flags: List[Dict]) -> List[Dict]:
"""Create actionable items for owners"""
actions = []
for flag in dead_flags:
actions.append({
'type': 'dead_flag_removal',
'flag_name': flag['name'],
'owner': flag['owner_email'],
'priority': 'high',
'suggested_action': 'Remove dead code and delete flag',
'reason': f"Expired {flag['days_since_last_use']} days ago, "
f"no usage in {flag['coverage_status']}",
'ticket_url': self._create_ticket(flag, 'Remove dead flag')
})
for flag in at_risk_flags:
days_left = (flag['expiration_date'] - datetime.now().date()).days
actions.append({
'type': 'expiration_warning',
'flag_name': flag['name'],
'owner': flag['owner_email'],
'priority': 'medium',
'suggested_action': 'Renew flag or remove code',
'reason': f"Expires in {days_left} days, "
f"last used {flag.get('days_since_last_use', 'N/A')} days ago",
'ticket_url': None
})
return actions
def _create_ticket(self, flag: Dict, title: str) -> str:
"""Auto-create ticket in Jira/GitHub"""
ticket = {
'title': f"[Dead Flag] {title}: {flag['name']}",
'description': self._generate_ticket_description(flag),
'assignee': flag['owner_email'],
'labels': ['feature-flag', 'dead-code', 'technical-debt'],
'project': flag['team']
}
# Create ticket via API
return f"https://jira.example.com/browse/TICKET-{uuid.uuid4().hex[:8]}"