fail-fast-no-hedging
Eliminate component hedging anti-patterns that mask infrastructure failures. Build systems that fail loudly when broken instead of limping along in degraded states. Critical for production reliability and operational visibility.
Fail-Fast Engineering: Architectural Honesty Over Silent Degradation
🚨 Core Principle
Hedging is treating required infrastructure as optional through defensive try/except blocks that mask failures as normal operation.
The Critical Question: Is this component required for the system to work correctly, or is it a genuine optional enhancement?
When required infrastructure fails, the system MUST fail loudly. When optional features fail, logging and continuing may be appropriate.
📋 Assessment Output Format (REQUIRED)
When analyzing a codebase, conclude with this structured list of all hedging issues found:
## Hedging Anti-Patterns Found in [directory/module name]
**N files with component hedging violations:**
1. **filename.py** (SEVERITY)
- Location: `function_name()` lines X-Y
- Issue: Brief description of what's wrong
- Hedging: Explanation of how it's treating required infrastructure as optional
- Impact: What happens in production when infrastructure fails
2. **filename.py** (SEVERITY)
- Location: `function_name()` lines X-Y
- Issue: Brief description of what's wrong
- Hedging: Explanation of how it's treating required infrastructure as optional
- Impact: What happens in production when infrastructure fails
Example (from lt_memory/ audit):
## Hedging Anti-Patterns Found in lt_memory/
**3 files with component hedging violations:**
1. **db_access.py** (HIGH SEVERITY)
- Location: `get_or_create_entity()` lines 916-933
- Issue: Returns `None` when database INSERT...RETURNING fails, masking query failure as "entity not found"
- Hedging: Docstring declares return type as `Entity`, implementation silently returns `None` on infrastructure failure
- Impact: Caller cannot distinguish between "entity doesn't exist" (legitimate) vs "database query failed" (infrastructure down)
2. **extraction.py** (HIGH SEVERITY)
- Location: `_parse_extraction_response()` lines 396-397 and 430
- Issue: Returns `[]` (empty list) when JSON parsing fails, instead of raising as docstring declares
- Hedging: Docstring says "Raises: ValueError" but code returns `[]` on parse failures
- Impact: Caller sees empty list and treats it as "no memories extracted" when actually LLM returned invalid JSON
This format makes all issues immediately scannable before remediation work begins.
🎯 Quick-Start Guide
When analyzing a new codebase:
-
Identify Infrastructure Dependencies
- Database connections
- Cache/session stores
- External APIs
- Message queues
- File systems
-
Apply Three Diagnostic Tests
- Semantic Distinction Test: Can you distinguish "no data" from "infrastructure down"?
- Never Executes Test: Will this fallback realistically run during normal operation?
- Contract Match Test: Does behavior match the docstring/type hints?
-
Look for These Red Flags
except Exception: return [] # Infrastructure failure → empty data except Exception: return False # Connection error → "not allowed" except Exception: return None # Database down → "not found"
🌍 Real-World Patterns from Production Codebases
Based on systematic removal of 40+ hedging anti-patterns across production systems, these specific patterns emerge repeatedly:
1. Infrastructure Failures Converted to Client Errors (CRITICAL)
Pattern: Catching database/service failures and raising ValidationError (400) instead of letting them propagate as 500s.
# REAL EXAMPLE: CNS API Layer
def execute_action(self, action: str, data: Dict) -> Dict:
try:
session_manager = get_shared_session_manager()
lt_db = LTMemoryDB(session_manager)
except Exception as e:
# Database down converted to "your input is invalid"!
if "connection" in str(e) or "database" in str(e):
raise ValidationError(f"Database connection failed: {e}")
Impact: Users see "Bad Request" when database is down. Monitoring doesn't alert (watches 500s, not 400s). Operators think users are sending bad data while infrastructure burns.
Fix: Remove business-layer exception translation. Let infrastructure exceptions bubble to API boundary where proper HTTP status translation happens.
2. The Availability Flag Plague (PERVASIVE)
Pattern: Setting self.component_available = False during init, then checking it hundreds of times throughout the codebase.
# REAL EXAMPLE: ValkeyClient with 200+ defensive checks
class ValkeyClient:
def __init__(self):
try:
self._init_connections()
self.valkey_available = True
except Exception:
self.valkey_available = False
def get(self, key: str) -> Optional[Any]:
if not self.valkey_available: # One of 200+ checks!
return None
return self.valkey.get(key)
Impact:
- Every operation has defensive check overhead
- Infrastructure failures silently masked as "feature disabled"
- Dead code paths when component is actually required
- False sense of "graceful degradation"
Fix: Remove availability tracking entirely. If component is required, fail at initialization. The "graceful degradation" never actually helps - it just delays the inevitable failure.
3. Silent Success Claims on Failure (DECEPTIVE)
Pattern: Returning {"success": True, "value": None} when infrastructure fails.
# REAL EXAMPLE: Calendar configuration endpoint
def get_calendar_config(self, user_id: str) -> Dict:
try:
config = credential_service.get_credential(user_id, "calendar_url")
return {"success": True, "calendar_url": config}
except Exception:
# Vault down? Claim success anyway!
return {"success": True, "calendar_url": None, "message": "Not configured"}
Impact: Client cannot distinguish "user hasn't configured calendar" from "credential service is down". UI shows "not configured" while Vault burns.
4. Job Registration Boolean Swallowing (TIME BOMB)
Pattern: Critical scheduled jobs return False on registration failure instead of raising.
# REAL EXAMPLE: Token renewal that fails silently
def register_jobs(self) -> bool:
try:
scheduler = get_scheduler()
success = scheduler.register_job(
job_id="vault-token-renewer",
func=self.renew_token,
trigger="interval",
days=7
)
return success # False if registration failed
except Exception:
return False # Import error? Scheduler down? Who knows!
Impact: Token renewal silently fails to register. System runs fine for 32 days, then authentication mysteriously breaks when token expires. No errors logged at startup.
5. Lazy Loading Creating False Optionality
Pattern: Deferring initialization with lazy loading, making required components appear optional.
# REAL EXAMPLE: Email service that's actually required
class Service:
def __init__(self):
self._email_service = None # Lazy loaded
def send_welcome_email(self, user_id: str):
if hasattr(self, '_email_service') and self._email_service:
self._email_service.send(...) # Silently skip if not loaded!
Impact: Required functionality (welcome emails) silently skipped when service fails to initialize. Users don't get onboarding emails, no errors logged.
6. Multi-Layer Exception Masking (DIAGNOSTIC HELL)
Pattern: Base class catches exceptions, subclass adds another layer, framework adds third layer.
# REAL EXAMPLE: Working memory trinket system
# Layer 1: Base trinket class
class BaseTrinket:
def handle_update_request(self):
try:
return self._generate_content()
except Exception:
return None # Mask all errors
# Layer 2: Event handler
def _handle_update_trinket(self, event):
try:
content = trinket.handle_update_request()
except Exception as e:
logger.warning(f"Trinket failed: {e}") # Second mask
# Layer 3: Individual trinket
class ReminderTrinket(BaseTrinket):
def _generate_content(self):
try:
reminders = self.get_reminders()
except Exception:
return [] # Third mask!
Impact: Database failure → returns [] → caught and returns None → caught and logged as warning. Original DatabaseError completely lost. Operators see "Trinket failed: 'NoneType' has no attribute 'format'" instead of "Database connection lost".
7. Data Corruption Hidden as Empty State
Pattern: JSON decode errors returning None instead of raising.
# REAL EXAMPLE: Database JSON columns
def fetch_as_dict(self, query: str) -> Optional[Dict]:
result = self.execute(query)
if result and result[0]:
try:
return json.loads(result[0])
except json.JSONDecodeError:
logger.warning("Failed to parse JSON")
return None # Corrupted data = no data!
Impact: Data corruption indistinguishable from NULL values. Corrupted user preferences silently become "no preferences". Data quality issues invisible until user complaints.
8. The hasattr() Vestigial Pattern
Pattern: Checking for attributes that are never set anywhere in the codebase.
# REAL EXAMPLE: Cache updater that doesn't exist
def _update_cache_if_pooled(self) -> None:
if hasattr(self, '_cache_updater') and self._cache_updater:
# This attribute is NEVER set anywhere!
try:
self._cache_updater(self.user_id, self._message_cache)
except Exception:
logger.warning("Cache update failed")
Impact: Dead code creating false architectural impressions. Future developers think "cache updates must be optional" when they're actually handled elsewhere entirely.
9. Partial Success Masquerading as Complete Success
Pattern: Continuing after required sub-operations fail.
# REAL EXAMPLE: User creation with broken setup
def create_user(email: str) -> str:
user_id = db.insert_user(email)
try:
initialize_user_preferences(user_id)
create_welcome_reminders(user_id)
send_welcome_email(user_id)
except Exception as e:
logger.error(f"User setup failed: {e}")
# Continue - user exists but broken!
return user_id # "Success!"
Impact: Users created in broken state. Can log in but missing preferences, reminders, welcome email. Support tickets: "Features don't work for some users."
10. Rate Limiter Fail-Closed Masquerade
Pattern: Security-motivated hedging that creates operational blindness.
# REAL EXAMPLE: Rate limiter "failing closed"
def is_allowed(self, identifier: str) -> Tuple[bool, int]:
try:
count = valkey.increment(f"rate:{identifier}")
return count <= self.limit, 0
except Exception:
# "Fail closed for security" - but identical to rate limited!
return False, self.window_seconds
Impact: Valkey outage = all users rate limited. Support flooded with "I can't log in" while ops thinks "high traffic day". Security theater creating availability problems.
📐 Pattern Library
Pattern 1: Infrastructure Masquerading
<pattern name="infrastructure-masquerade"> <anti_pattern> def operation([PARAMS]) -> [RETURN_TYPE]: try: result = [REQUIRED_INFRASTRUCTURE].query() return result except Exception: return [SAFE_DEFAULT] # Infrastructure failure looks like [NORMAL_STATE] </anti_pattern><fail_fast> def operation([PARAMS]) -> [RETURN_TYPE]: result = [REQUIRED_INFRASTRUCTURE].query() # Raises on infrastructure failure return result # Only returns actual data or legitimate empty state </fail_fast>
<diagnostic> Can caller distinguish between "[NO_DATA]" and "[INFRASTRUCTURE_DOWN]"? </diagnostic> </pattern>Examples of [SAFE_DEFAULT]: [], None, False, 0, {}
Examples of [REQUIRED_INFRASTRUCTURE]: database, cache, auth_service, message_queue
Pattern 2: False Optionality
<pattern name="false-optionality"> <anti_pattern> class Service: def __init__(self): self._component = None # Lazy loading creates false impression@property
def component(self):
if self._component is None:
self._component = initialize_component()
return self._component
def operation(self):
if hasattr(self, '_component') and self._component: # Defensive checks
return self._component.do_work()
return [DEGRADED_RESULT]
</anti_pattern>
<fail_fast> class Service: def init(self): self.component = initialize_component() # Fail at startup if broken
def operation(self):
return self.component.do_work() # No defensive checks needed
</fail_fast>
<diagnostic> Is the component truly optional, or are we just afraid of startup failures? </diagnostic> </pattern>Pattern 3: Partial Success Masking
<pattern name="partial-success"> <anti_pattern> def create_resource([PARAMS]) -> [ID_TYPE]: resource_id = database.insert([DATA])try:
initialize_related([resource_id]) # Required setup
except Exception:
logger.error("Setup failed")
# Continue - resource exists but broken
return resource_id # Partial success returned as complete
</anti_pattern>
<fail_fast> def create_resource([PARAMS]) -> [ID_TYPE]: resource_id = database.insert([DATA]) initialize_related([resource_id]) # Fails → transaction rolls back return resource_id # Only returns if fully initialized </fail_fast>
<diagnostic> Are we creating broken/incomplete entities that will fail later? </diagnostic> </pattern>Pattern 4: Safe Defaults on Error
<pattern name="safe-defaults"> <anti_pattern> def get_metric([PARAMS]) -> [NUMERIC_TYPE]: try: result = metrics_service.query([PARAMS]) return result.value except Exception: return 0 # Service down? Return zero!def get_config([PARAMS]) -> Dict: try: return config_service.fetch([KEY]) except Exception: return {"success": True, "value": None} # Claim success on failure! </anti_pattern>
<fail_fast> def get_metric([PARAMS]) -> [NUMERIC_TYPE]: result = metrics_service.query([PARAMS]) # Raises on service failure return result.value # Zero only when metric genuinely is zero
def get_config([PARAMS]) -> Dict: config = config_service.fetch([KEY]) # Raises on service failure return {"success": True, "value": config} </fail_fast>
<diagnostic> Does the "safe" default hide infrastructure problems from operators? </diagnostic> </pattern>Pattern 5: The "Never Executes" Fallback
<pattern name="never-executes"> <anti_pattern> def get_or_create_resource([PARAMS]) -> [RESOURCE_TYPE]: result = database.insert_returning([DATA])if result:
return [RESOURCE_TYPE](**result)
# This fallback will NEVER execute in correct operation
# INSERT...RETURNING should always return a result
# If it doesn't, infrastructure is broken
fetch_query = "SELECT * FROM [TABLE] WHERE ..."
existing = database.query(fetch_query)
return [RESOURCE_TYPE](**existing) if existing else None
</anti_pattern>
<fail_fast> def get_or_create_resource([PARAMS]) -> [RESOURCE_TYPE]: result = database.insert_returning([DATA])
if not result:
raise RuntimeError(
f"INSERT...RETURNING failed - database operation broken, "
f"not a recoverable race condition"
)
return [RESOURCE_TYPE](**result)
</fail_fast>
<diagnostic> Critical Question: "Will this fallback code realistically execute when the system is operating correctly?" - YES → Legitimate defensive programming (real race conditions) - NO → Hedging that masks the real error </diagnostic> </pattern>이 스킬의 파일
이 스킬에는 보조 파일이 없습니다.