The Problem
A product manager gives a developer a requirement: "Users should be able to reset their password by entering their email. If the email exists in our system, send a reset link. If not, show a generic message saying 'If an account exists, you will receive an email.'"
The developer asks an AI assistant to implement this. The AI generates code that:
- Queries the database for the email
- If found, generates a token and sends an email
- If not found, returns the generic message
The code works. Tests pass. But the AI made three assumptions the spec didn't state:
- It logs "Password reset requested for unknown email: X" -- leaking which emails are registered via logs (CWE-117)
- It doesn't rate-limit reset requests -- allowing email bombing
- It uses the same token for multiple requests -- allowing token replay
The spec didn't mention logging, rate-limiting, or token uniqueness. The AI filled in those gaps with the most probable implementation -- which happened to introduce three security vulnerabilities. Spec-first development catches this by forcing the developer to think through these concerns before the AI generates code.
Writing behavioral specifications
A behavioral specification has five components:
- Functional requirements: What the function should do
- Input domain: What inputs it should accept (including invalid ones)
- Output contract: What it should return and when
- Failure modes: How it should handle errors
- Invariants: Properties that must always hold
Example specification for the password reset function:
Function: request_password_reset(email: str) -> dict
Functional requirements:
- If email exists in users table, generate a unique reset token (UUID4),
store it with a 15-minute expiry, and send a reset email.
- If email does not exist, do nothing but return the same response.
- Response must be identical regardless of whether email exists (no user enumeration).
Input domain:
- Valid email strings (any format)
- Empty string
- None
- Very long strings (>1000 chars)
- Strings with special characters and SQL injection attempts
Output contract:
- Always returns {"message": "If an account exists, you will receive an email."}
- Never returns whether the email was found
- Never raises an exception (all errors are caught and logged safely)
Failure modes:
- Database error: log internally, return generic message
- Email send error: log internally, return generic message
- Rate limit exceeded: return generic message, do not send email
Invariants:
- Response is identical for existing and non-existing emails (timing-safe)
- Reset token is unique per request (UUID4)
- Reset token expires after 15 minutes
- No user-identifiable information in logs (CWE-117 compliance)
- Rate limited: max 3 requests per email per hour
The spec is the only source of truth
When the AI generates code, the spec is the only source of truth for correctness. The AI does not know about your security requirements, your rate-limiting policy, or your logging standards. If the spec doesn't mention them, the AI will make assumptions -- and those assumptions are where vulnerabilities live. The spec must be explicit about security, performance, and operational concerns, not just functional behavior.
Translating specs into pytest tests
Once the spec is written, translate it into pytest test cases. Each spec component becomes test cases:
import pytest
class TestPasswordReset:
# Functional requirements
def test_existing_email_sends_reset(self):
result = request_password_reset("user@example.com")
assert result == {"message": "If an account exists, you will receive an email."}
def test_nonexistent_email_returns_same_message(self):
result = request_password_reset("nonexistent@example.com")
assert result == {"message": "If an account exists, you will receive an email."}
# Input domain
def test_empty_string(self):
result = request_password_reset("")
assert result["message"] # Should not crash
def test_none_input(self):
result = request_password_reset(None)
assert result["message"] # Should not crash
def test_very_long_string(self):
result = request_password_reset("a" * 10000 + "@example.com")
assert result["message"]
# Invariants
def test_response_identical_for_existing_and_nonexistent(self):
r1 = request_password_reset("user@example.com")
r2 = request_password_reset("nonexistent@example.com")
assert r1 == r2 # No user enumeration
def test_rate_limiting(self):
for _ in range(3):
request_password_reset("user@example.com")
result = request_password_reset("user@example.com")
assert result["message"] # Should still return generic, but not send email
These tests are written before the AI generates code. The AI's prompt includes the spec and the tests:
Implement request_password_reset(email: str) -> dict according to this specification:
[spec here]
The following tests must pass:
[tests here]
Requirements:
- Use UUID4 for reset tokens
- Store tokens with 15-minute expiry
- Rate limit: max 3 requests per email per hour
- No user-identifiable information in logs
- Response must be identical for existing and non-existing emails
A developer writes a spec for a calculate_discount(price, customer_tier) function. The spec says: "Returns the discounted price. Gold tier gets 20%, Silver gets 10%, Bronze gets 5%." The AI generates code that returns negative prices when the discount exceeds the price (e.g., price=$5, Gold tier -> -$1). What spec component was missing, and how would spec-first development have caught this?
The spec was missing an invariant: the discounted price must never be negative. This is a common AI code defect pattern -- the AI generates the most straightforward implementation (price (1 - discount)) without considering edge cases where the discount exceeds the price. Spec-first development catches this because the developer writes tests from the spec before the AI generates code. If the developer includes the invariant 'discounted price >= 0' in the spec, they will write a test case for price=$5, tier=Gold and assert the result is >= 0. The AI must then implement max(0, price (1 - discount)) to pass the test. Without the spec-first approach, the developer would likely test only typical cases (price=$100, tier=Gold -> $80) and miss the edge case.
Handling ambiguous specs
Ambiguity is where AI code gets dangerous. When the spec is ambiguous, the AI fills in the gaps with the most probable implementation -- which may not match your intent. Three strategies for handling ambiguity:
- Make ambiguity explicit: If the spec doesn't cover a case, add a test case for it and define the expected behavior. "If customer_tier is not recognized, return the original price (no discount)."
- Test the boundaries: For every ambiguous boundary, write a test. "If price is 0, discounted price is 0. If price is negative, raise ValueError."
- Use property-based testing for invariants: Instead of testing specific values, test properties. "For all non-negative prices and all valid tiers, discounted price >= 0." Hypothesis will generate thousands of inputs to verify this.
A spec says: "The function should return the first N items from a list." The AI generates return list[:N]. This works for most cases but returns the full list when N > len(list) (Python slicing behavior). Is this a spec ambiguity, and how should it be handled?
This is a classic spec ambiguity. 'First N items' is ambiguous when N > len(list): does it mean 'up to N items' (Python default) or 'exactly N items' (which would require padding or an error)? The AI chose Python's default behavior, which may not match the product requirement. The fix is to add a test case: test_n_greater_than_list_length() with the expected behavior (return full list, raise ValueError, or pad), and update the spec to be explicit. This demonstrates why specs must cover edge cases -- the AI will always choose some behavior for ambiguous cases, but it may not be the behavior you want.