Prompt Details
Model
(claude-5-5-sonnet)
Token size
5,223
Example input
[PROJECT_CONTEXT]: E-Commerce Checkout API Backend: Python FastAPI Database: PostgreSQL Purpose: Calculate product discounts and final checkout prices.
[CODE_CHANGES]: A developer modified the discount calculation endpoint but did not implement proper input validation.
[TECH_STACK]: Python 3.12 FastAPI Pydantic PostgreSQL Pytest
[DEPENDENCY_AND_TEST_CONTEXT]: FastAPI handles API requests. Pydantic handles request validation. Existing tests cover only normal discount calculations. No boundary-value tests are available.
[REVIEW_REQUIREMENTS]: Find calculation defects. Identify security risks. Improve input validation. Refactor the discount service. Generate unit and integration tests. Preserve existing API compatibility wherever possible.
Example output
### PHASE 1 β CODEBASE INTAKE & REVIEW SCOPE
Review Started
### 1.1 Supplied Code
Original implementation:
File: `discount_service.py`
```python
def calculate_discount(price, discount_percentage):
discount = price * discount_percentage / 100
final_price = price - discount
return final_price
```
File: `checkout.py`
```python
from fastapi import FastAPI
from discount_service import calculate_discount
app = FastAPI()
@app.get("/checkout")
def checkout(price: float, discount: float):
final_price = calculate_discount(price, discount)
return {
"original_price": price,
"discount": discount,
"final_price": final_price
}
```
File: `test_checkout.py`
```python
def test_discount():
result = calculate_discount(1000, 10)
assert result == 900
```
### 1.2 Scope Classification
| Review area | Status |
| ------------------------ | --------------- |
| Source code | Partial |
| Modified files | 2 |
| Existing tests | 1 supplied test |
| Dependencies | Partial |
| Database schema | Not supplied |
| Authentication | Unknown |
| Deployment configuration | Not supplied |
| Git diff | Not supplied |
Assessment: This is a multi-file partial-context review, not a complete repository audit.
### 1.3 Initial Observations
* No validation for negative prices.
* No validation for discount percentages above 100.
* No explicit monetary precision handling.
* No invalid-input tests.
* API error behavior is undefined for invalid values.
Phase 1 Result: Scope established. Further repository inspection is required before claiming complete coverage.
### PHASE 2 β CHANGE IMPACT & DEPENDENCY ANALYSIS
### 2.1 Dependency Map
```text
Client Application
|
v
FastAPI Endpoint
|
v
Discount Service
|
v
Final Price Response
```
### 2.2 Dependency Findings
| Component | Observation | Risk |
| ---------------- | ------------------------------------- | ------- |
| FastAPI | Handles query parameters | Low |
| Pydantic | Available but no explicit model shown | Medium |
| Discount service | Accepts unrestricted values | High |
| PostgreSQL | No database interaction shown | Unknown |
| Pytest | Only one test supplied | Medium |
### 2.3 Findings
DEP-001: Missing explicit validation layer
* Severity: Medium
* Evidence: Endpoint accepts unrestricted floating-point inputs.
* Impact: Invalid business values can reach the calculation function.
* Recommendation: Introduce request validation using Pydantic.
DEP-002: Dependency compatibility
* Severity: Informational
* Evidence: Dependency versions and lockfile are missing.
* Recommendation: Verify FastAPI, Pydantic and Python compatibility.
Phase 2 Result: Validation architecture needs improvement. Dependency vulnerabilities cannot be confirmed from supplied evidence.
### PHASE 3 β CORRECTNESS & LOGIC DEFECT REVIEW
2 Confirmed Defects
### BUG-001: Negative Discount Percentage Accepted
Location: `discount_service.py`
Problem:
```python
calculate_discount(1000, -10)
```
Actual result:
```text
1100
```
Expected result:
```text
Reject invalid discount percentage.
```
Severity: High
Why it matters:
* Customers could receive incorrect checkout totals.
* Business revenue calculations may become inconsistent.
* Invalid financial values may enter downstream workflows.
Recommended correction: Enforce a discount range of 0β100.
### BUG-002: Discount Above 100% Accepted
Input:
```python
calculate_discount(1000, 150)
```
Actual result:
```text
-500
```
Expected result:
```text
Reject invalid discount percentage.
```
Severity: High
Recommended correction: Validate the discount percentage before calculation.
### BUG-003: Negative Product Price Accepted
Input:
```python
calculate_discount(-500, 10)
```
Actual result:
```text
-450
```
Expected result:
```text
Reject negative product prices.
```
Severity: Medium
### Correctness Summary
| Finding | Severity | Confidence |
| ------- | -------- | ---------- |
| BUG-001 | High | Confirmed |
| BUG-002 | High | Confirmed |
| BUG-003 | Medium | Confirmed |
### PHASE 4 β DESIGN FLAW & ARCHITECTURE REVIEW
### 4.1 Design Assessment
DES-001: Missing Input Validation Layer
Current architecture:
```text
API β Calculation Function
```
Recommended architecture:
```text
API
|
v
Request Validation
|
v
Discount Service
|
v
Validated Result
```
Problem: The calculation function assumes every input is valid.
Improvement: Validate inputs at the API boundary and protect the calculation service independently.
DES-002: Mixed Responsibilities
The current endpoint handles request processing and calculation orchestration without an explicit validation contract.
Recommended separation:
* API layer: Request and response handling.
* Validation layer: Input constraints.
* Service layer: Discount calculations.
* Test layer: Business-rule verification.
DES-003: Monetary Precision
Using floating-point numbers for financial calculations can introduce rounding inaccuracies.
Recommended approach: Use Python `Decimal` for monetary calculations.
Phase 4 Result: Targeted refactoring is recommended. A larger architectural redesign is unnecessary.
### PHASE 5 β CODE SMELL & MAINTAINABILITY AUDIT
| ID | Code smell | Impact |
| ------ | ----------------------------- | ------------------------- |
| SM-001 | No input validation | Incorrect calculations |
| SM-002 | Floating-point money | Precision issues |
| SM-003 | No named business constraints | Difficult maintenance |
| SM-004 | Minimal test coverage | Regression risk |
| SM-005 | No explicit error contract | Inconsistent API behavior |
### Recommended Improvements
* Introduce named validation constraints.
* Use `Decimal` for monetary values.
* Separate validation from calculation.
* Add meaningful exception handling.
* Expand test coverage.
Maintainability Rating: Needs Improvement.
### PHASE 6 β SECURITY & VULNERABILITY REVIEW
Potential Risk Assessment
### SEC-001: Unrestricted Financial Input
* Severity: Medium
* Category: Input validation.
* Evidence: API accepts unrestricted price and discount parameters.
* Threat scenario: An external client submits invalid numerical values.
* Impact: Incorrect checkout calculations and possible business-rule abuse.
* Confidence: High that validation is missing; actual exploitability depends on downstream checkout controls.
Mitigation: Enforce server-side validation.
### SEC-002: Unbounded Numerical Inputs
* Severity: Low to Medium
* Category: Resource and input handling.
* Evidence: No explicit bounds are shown.
* Impact: Extremely large or malformed numerical inputs may cause unexpected behavior.
* Confidence: Medium.
Mitigation: Apply reasonable input bounds and request validation.
### Security Areas Not Verified
* Authentication.
* Authorization.
* SQL injection.
* Database permissions.
* Secret management.
* CORS.
* CSRF.
* Rate limiting.
These cannot be confirmed without additional application context.
Security Recommendation: Do not consider the endpoint production-ready until input validation and relevant checkout authorization controls are verified.
### PHASE 7 β PERFORMANCE & RESOURCE EFFICIENCY
### 7.1 Performance Findings
PERF-001: Floating-Point Financial Calculation
* Location: `discount_service.py`
* Impact: Primarily financial accuracy, not necessarily execution speed.
* Recommendation: Use `Decimal`.
PERF-002: No Significant Algorithmic Bottleneck
The calculation uses constant-time arithmetic.
Time complexity:
O(1)
Space complexity:
O(1)
PERF-003: Request Limits
No explicit input bounds are shown.
Recommendation:
* Limit numerical input sizes.
* Use framework-level validation.
* Consider request rate limiting at the application or infrastructure level.
Performance Rating: Good for computational complexity; operational performance remains unknown.
### PHASE 8 β API, DATA & CONTRACT COMPATIBILITY
### 8.1 Existing API
```http
GET /checkout?price=1000&discount=10
```
Response:
```json
{
"original_price": 1000,
"discount": 10,
"final_price": 900
}
```
### 8.2 Compatibility Concerns
| Contract | Assessment |
| ----------------------------- | ---------------- |
| Endpoint path | Preserve |
| Query parameter names | Preserve |
| Successful response fields | Preserve |
| Successful response semantics | Preserve |
| Invalid-input behavior | Needs definition |
| Numeric serialization | Verify |
Recommendation: Retain the endpoint and parameter names. Reject invalid values with HTTP 422.
Because the existing API has no documented error contract, confirm client expectations before deployment.
### PHASE 9 β TESTABILITY & EXISTING TEST QUALITY
### 9.1 Existing Test
```python
def test_discount():
result = calculate_discount(1000, 10)
assert result == 900
```
### 9.2 Test Quality Assessment
| Test requirement | Existing coverage |
| ------------------- | ----------------- |
| Normal discount | Yes |
| Zero discount | No |
| 100% discount | No |
| Negative discount | No |
| Discount above 100% | No |
| Negative price | No |
| Decimal precision | No |
| Invalid API request | No |
### 9.3 Required Test Matrix
| Test ID | Input | Expected result |
| ------- | --------- | --------------- |
| TC-001 | 1000, 10 | 900 |
| TC-002 | 1000, 0 | 1000 |
| TC-003 | 1000, 100 | 0 |
| TC-004 | 1000, -10 | Reject |
| TC-005 | 1000, 150 | Reject |
| TC-006 | -500, 10 | Reject |
| TC-007 | 99.99, 10 | 89.99 |
Testability Rating: Needs Improvement.
### PHASE 10 β REFACTORING STRATEGY
### Proposed Refactoring
| ID | Improvement | Priority |
| ------- | ---------------------------- | -------- |
| REF-001 | Add input validation | P0 |
| REF-002 | Use Decimal | P1 |
| REF-003 | Separate calculation service | P1 |
| REF-004 | Add API error handling | P1 |
| REF-005 | Expand automated tests | P1 |
### Recommended Architecture
```text
checkout/
|
|-- main.py
|-- schemas.py
|-- discount_service.py
|-- tests/
|-- test_discount.py
|-- test_checkout_api.py
```
This is a proposed structure, not a claim about the existing repository.
### PHASE 11 β PRIORITIZED REMEDIATION ROADMAP
TASK-001: Enforce Financial Input Validation
* Finding: BUG-001, BUG-002, BUG-003.
* Complexity: Low.
* Risk of delay: Invalid financial calculations.
* Acceptance criteria: Negative prices and discount percentages outside 0β100 are rejected.
TASK-002: Implement Decimal Calculations
* Finding: PERF-001.
* Complexity: Low.
* Acceptance criteria: Financial calculations use deterministic decimal arithmetic.
TASK-003: Add API Validation
* Finding: DEP-001.
* Complexity: Low.
* Acceptance criteria: Invalid requests return HTTP 422.
TASK-004: Expand Regression Tests
* Finding: Test coverage gaps.
* Complexity: Medium.
* Acceptance criteria: All identified boundary cases pass.
TASK-005: Improve Module Separation
* Complexity: Medium.
* Acceptance criteria: Validation and calculation responsibilities are clearly separated.
TASK-006: Documentation and Naming Cleanup
* Complexity: Low.
* Acceptance criteria: Business constraints and calculation behavior are documented.
### PHASE 12 β REFACTORED CODE GENERATION
Implementation Example
### A. Original Problem
The original service accepts invalid prices and discount percentages and uses floating-point arithmetic.
### B. Refactored Code
File: `discount_service.py`
```python
from decimal import Decimal, ROUND_HALF_UP
def calculate_discount(
price: Decimal,
discount_percentage: Decimal
) -> Decimal:
if not price.is_finite():
raise ValueError("Price must be finite")
if not discount_percentage.is_finite():
raise ValueError("Discount must be finite")
if price < 0:
raise ValueError("Price cannot be negative")
if not Decimal("0") <= discount_percentage <= Decimal("100"):
raise ValueError("Discount must be between 0 and 100")
discount = (
price * discount_percentage / Decimal("100")
)
final_price = price - discount
return final_price.quantize(
Decimal("0.01"),
rounding=ROUND_HALF_UP
)
```
### C. Refactored API
File: `checkout.py`
```python
from decimal import Decimal
from fastapi import FastAPI, Query, HTTPException
from discount_service import calculate_discount
app = FastAPI()
@app.get("/checkout")
def checkout(
price: Decimal = Query(ge=0, max_digits=12, decimal_places=2),
discount: Decimal = Query(
ge=0,
le=100,
max_digits=5,
decimal_places=2
)
):
try:
final_price = calculate_discount(price, discount)
return {
"original_price": price,
"discount": discount,
"final_price": final_price
}
except ValueError as error:
raise HTTPException(
status_code=422,
detail=str(error)
)
```
### D. What Improved?
* Added server-side validation.
* Rejected negative prices.
* Rejected invalid discount percentages.
* Added decimal arithmetic.
* Added two-decimal monetary rounding.
* Preserved the endpoint and query parameter names.
* Preserved successful response field names.
Important: This is an implementation example based on the supplied snippets. The original project has not been modified. Exact compatibility with its installed FastAPI and Pydantic versions must be verified.
### E. Integration Instructions
* Replace the original calculation implementation.
* Update the checkout endpoint.
* Confirm installed package versions.
* Run existing tests.
* Add new boundary-value tests.
* Verify JSON serialization of Decimal values.
* Validate API compatibility with existing clients.
### PHASE 13 β TEST COVERAGE & TEST GENERATION
### 13.1 Unit Test Code
File: `test_discount.py`
```python
import pytest
from decimal import Decimal
from discount_service import calculate_discount
def test_normal_discount():
result = calculate_discount(
Decimal("1000"),
Decimal("10")
)
assert result == Decimal("900.00")
def test_zero_discount():
result = calculate_discount(
Decimal("1000"),
Decimal("0")
)
assert result == Decimal("1000.00")
def test_full_discount():
result = calculate_discount(
Decimal("1000"),
Decimal("100")
)
assert result == Decimal("0.00")
@pytest.mark.parametrize(
"price,discount",
[
("1000", "-10"),
("1000", "150"),
("-500", "10"),
]
)
def test_invalid_inputs(price, discount):
with pytest.raises(ValueError):
calculate_discount(
Decimal(price),
Decimal(discount)
)
def test_decimal_rounding():
result = calculate_discount(
Decimal("99.99"),
Decimal("10")
)
assert result == Decimal("89.99")
```
### 13.2 API Integration Test
File: `test_checkout_api.py`
```python
from fastapi.testclient import TestClient
from checkout import app
client = TestClient(app)
def test_valid_checkout():
response = client.get(
"/checkout?price=1000&discount=10"
)
assert response.status_code == 200
data = response.json()
assert data["final_price"] == 900.0
def test_invalid_discount():
response = client.get(
"/checkout?price=1000&discount=150"
)
assert response.status_code == 422
def test_negative_price():
response = client.get(
"/checkout?price=-500&discount=10"
)
assert response.status_code == 422
```
### 13.3 Additional Required Tests
| Test ID | Category | Objective |
| ------- | ----------- | -------------------------------- |
| T-001 | Unit | Normal calculation |
| T-002 | Unit | Zero discount |
| T-003 | Unit | Full discount |
| T-004 | Unit | Negative price |
| T-005 | Unit | Excessive discount |
| T-006 | Unit | Decimal rounding |
| T-007 | Integration | Valid API request |
| T-008 | Integration | Invalid API request |
| T-009 | Regression | Existing response fields |
| T-010 | Security | Invalid numerical input handling |
Note: These tests are generated examples, not executed test results.
### PHASE 14 β REGRESSION RISK & VALIDATION GATES
### 14.1 Validation Checklist
| Gate | Required check | Expected result |
| ------------- | ----------------------- | --------------------------------- |
| Formatting | Ruff formatter | No formatting errors |
| Linting | Ruff | No relevant lint errors |
| Type checking | mypy | No relevant type errors |
| Unit testing | pytest | All tests pass |
| Integration | FastAPI TestClient | Correct HTTP responses |
| Security | Input validation review | Invalid inputs rejected |
| Dependencies | Package audit | No unresolved relevant advisories |
| Regression | Existing API tests | Existing behavior preserved |
| Performance | Representative workload | No unacceptable regression |
| Build | Application startup | Successful startup |
### 14.2 Example Commands
```bash
pip install fastapi pytest httpx
```
```bash
ruff check .
```
```bash
pytest -v
```
```bash
mypy .
```
These are suggested commands. They have not been executed.
### 14.3 Regression Risks
* Decimal serialization may change JSON numeric representation.
* New validation may reject previously accepted invalid inputs.
* Client applications may depend on previous error behavior.
* Rounding rules may affect displayed totals.
Recommendation: Validate client compatibility before deployment.
### PHASE 15 β ENGINEERING QUALITY & ACCEPTANCE
### 15.1 Quality Scorecard
| Engineering area | Rating |
| ----------------------- | ----------------- |
| Correctness | Needs Improvement |
| Security | Needs Improvement |
| Performance | Good |
| Maintainability | Needs Improvement |
| Architecture | Needs Improvement |
| Dependency safety | Unknown |
| Compatibility | Needs Improvement |
| Testability | Needs Improvement |
| Operational reliability | Unknown |
### 15.2 Merge Recommendation
REQUEST CHANGES
Current implementation
The supplied code should not be approved for production checkout use until financial input validation and regression tests are implemented.
### 15.3 Conditions for Approval
* Negative prices must be rejected.
* Discount percentages must be restricted to 0β100.
* Monetary calculations must use an appropriate precision strategy.
* All generated regression tests must pass.
* Existing API compatibility must be verified.
* Dependency versions must be checked.
### PHASE 16 β FINAL SENIOR ENGINEERING REVIEW REPORT
### π 16.1 Executive Review Summary
Project: E-Commerce Checkout API
Technology: Python + FastAPI
Review outcome: Important correctness and validation defects identified.
Main concerns:
* Negative discount acceptance.
* Discount above 100% acceptance.
* Negative price acceptance.
* Floating-point monetary calculations.
* Insufficient test coverage.
### π 16.2 Review Scope
* 2 source files reviewed.
* 1 existing test reviewed.
* 3 confirmed correctness defects.
* 2 potential security/resource concerns.
* Full repository not supplied.
### π 16.3 Change Impact
Affected components:
* Checkout API.
* Discount calculation service.
* Automated testing.
* Client-side checkout integration.
### π¨ 16.4 Prioritized Findings
| ID | Severity | Category | Confidence |
| -------- | ---------- | ----------------- | ---------- |
| BUG-001 | High | Correctness | High |
| BUG-002 | High | Correctness | High |
| BUG-003 | Medium | Correctness | High |
| SEC-001 | Medium | Security | High |
| SEC-002 | Low-Medium | Resource handling | Medium |
| SM-001 | Medium | Maintainability | High |
| PERF-001 | Medium | Precision | High |
### ποΈ 16.5 Design & Maintainability
Recommended changes:
* Introduce explicit input validation.
* Separate business logic.
* Use Decimal for monetary calculations.
* Establish consistent API error handling.
* Improve unit and integration testing.
### π 16.6 Security Review
* Input validation is insufficient.
* Authorization behavior is unknown.
* Authentication configuration is unknown.
* Database security cannot be assessed from supplied code.
* Further security testing is required.
### β‘ 16.7 Performance Review
* Calculation complexity is O(1).
* No demonstrated algorithmic bottleneck.
* Numerical precision requires improvement.
* Production latency and throughput remain unmeasured.
### π οΈ 16.8 Refactoring Blueprint
Recommended implementation order:
* Input validation.
* Decimal calculations.
* API error handling.
* Unit tests.
* Integration tests.
* Compatibility validation.
* Deployment verification.
### π§ͺ 16.9 Test Coverage Requirements
Prioritize:
* Normal calculations.
* Minimum and maximum discount values.
* Negative inputs.
* Decimal rounding.
* Invalid API requests.
* API response compatibility.
### π 16.10 Remediation Backlog
| Task | Priority | Complexity |
| -------------------- | -------- | ---------- |
| Input validation | P0 | Low |
| Decimal calculations | P1 | Low |
| API error handling | P1 | Low |
| Regression testing | P1 | Medium |
| Architecture cleanup | P2 | Medium |
| Documentation | P3 | Low |
### β
16.11 Validation Gates
Before merging:
* Formatting passes.
* Linting passes.
* Type checking passes.
* Unit tests pass.
* Integration tests pass.
* Security review completed.
* Dependencies checked.
* API compatibility verified.
* Build succeeds.
### β οΈ 16.12 Residual Risks
The following remain unresolved:
* Actual database integration.
* User authentication and authorization.
* Payment gateway integration.
* Production configuration.
* Dependency vulnerability status.
* Existing client compatibility.
### 16.13 Final Engineering Recommendation
REQUEST CHANGES
The original implementation contains confirmed financial calculation defects. The proposed refactoring addresses the identified input-validation and precision problems, but repository integration and execution testing are still required.
### 16.14 Implementation Handoff
Developer responsibilities:
* Implement input validation.
* Update the calculation service.
* Add automated regression tests.
* Verify API response compatibility.
* Execute security and dependency checks.
Reviewer responsibilities:
* Verify the code changes.
* Inspect test assertions.
* Review Decimal serialization.
* Confirm all acceptance criteria.
* Approve only after validation succeeds.
### 16.15 Final Code Quality Blueprint
Priority engineering actions
* Fix unrestricted discount and price inputs.
* Replace floating-point financial calculations with Decimal.
* Improve validation and error handling.
* Generate unit, integration and regression tests.
* Verify security and dependency compatibility.
* Run all validation gates before merging.
Final status
Review completeness
16/16 phases demonstrated
Actual execution
Not performed
Merge recommendation
REQUEST CHANGES
### π― FINAL SAMPLE TEST RESULT
| Evaluation criterion | Result |
| --------------------------- | ------------ |
| Code inspection | Demonstrated |
| Change impact analysis | Demonstrated |
| Dependency analysis | Demonstrated |
| Bug detection | Demonstrated |
| Architecture review | Demonstrated |
| Code smell detection | Demonstrated |
| Security review | Demonstrated |
| Performance review | Demonstrated |
| API compatibility | Demonstrated |
| Refactoring strategy | Demonstrated |
| Refactored code | Generated |
| Unit test generation | Generated |
| Integration test generation | Generated |
| Regression planning | Demonstrated |
| Prioritized roadmap | Generated |
| Final engineering report | Generated |
SAMPLE TEST COMPLETED
Overall assessment: The SLCRS-3499 prompt successfully demonstrates an end-to-end senior-level code review workflow using a realistic Python/FastAPI project.
Important distinction: All findings are based on the illustrative code supplied in this sample. No actual repository, test execution, benchmark, or security scan was performed.
By purchasing this prompt, you agree to our terms of service
CLAUDE-5-5-SONNET
Senior-Level Code Review & Refactoring Strategist
Turn complex code changes into production-quality, maintainable software.
This advanced engineering prompt acts as a senior software engineer, principal code reviewer, application security reviewer, and refactoring strategist.
It analyzes complete code changes alongside their dependencies and surrounding codebase context to identify correctness defects, architectural weaknesses, security vulnerabilities, performance bottlenecks, code smells.
...more
Added 1 day ago
