File size: 11,322 Bytes
27d7338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351c200
27d7338
351c200
27d7338
351c200
 
 
 
 
27d7338
 
 
351c200
27d7338
351c200
 
 
 
 
 
 
 
27d7338
351c200
 
27d7338
 
 
 
 
 
 
 
 
 
 
351c200
27d7338
351c200
27d7338
351c200
27d7338
351c200
 
 
 
 
27d7338
351c200
 
 
 
27d7338
351c200
27d7338
 
 
 
 
351c200
 
27d7338
351c200
27d7338
 
351c200
 
27d7338
 
351c200
 
 
 
27d7338
 
 
bd428dc
351c200
 
27d7338
bd428dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a94b1c
27d7338
40ab31f
 
 
 
 
 
 
351c200
 
27d7338
351c200
27d7338
351c200
27d7338
351c200
27d7338
351c200
27d7338
 
351c200
27d7338
351c200
 
27d7338
 
351c200
27d7338
351c200
27d7338
 
 
 
 
 
351c200
 
 
 
 
 
27d7338
351c200
 
 
 
 
 
 
 
 
 
27d7338
351c200
 
 
27d7338
 
 
 
351c200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27d7338
 
351c200
 
 
 
 
 
27d7338
351c200
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
---
title: Code Review OpenEnv
emoji: "\U0001F50E"
colorFrom: indigo
colorTo: purple
sdk: docker
app_port: 7860
pinned: false
---

# Code Review OpenEnv

A deterministic, OpenEnv-style benchmark environment for evaluating AI code review agents. The agent receives buggy Python pull requests, leaves structured review comments, and is graded on precision, recall, and **semantic understanding** against ground-truth bugs.

**Live Space:** https://deepparmar-code-review.hf.space

---

## Environment Description & Motivation

Traditional code review benchmarks measure LLMs on a binary metric: *Did the model flag the correct line?* As frontier models approach ceiling performance on these shallow evaluations, we need environments that test deeper capabilities.

This environment simulates **real-world code review** β€” a task that software engineers perform daily. An AI agent must:
1. Read buggy Python code (pull request diffs)
2. Identify security vulnerabilities, logic bugs, and performance issues
3. Explain *why* something is broken (not just *where*)
4. Avoid false positives and deliberately planted traps

---

## Action Space

| Operation | Parameters | Description |
|---|---|---|
| `add_comment` | `line_number`, `severity`, `category`, `message`, `confidence` | Flag a bug with explanation + Telemetry calibration tracking |
| `approve` | `summary` | Approve the PR (risky if bugs remain) |
| `request_changes` | `summary` | Request changes with summary |
| `done` | _(none)_ | Finish review, trigger final grading |
| `inspect_file` | `filename` | View a specific file (hard task) |
| `inspect_lines` | `filename`, `start_line`, `end_line` | View specific lines |

**Severity:** `critical` | `major` | `minor` | `nit`
**Category:** `bug` | `security` | `performance` | `style`

## Observation Space

| Field | Type | Description |
|---|---|---|
| `task_id` | `str` | `easy`, `medium`, or `hard` |
| `pr_title` / `pr_description` | `str` | Pull request metadata |
| `full_file` | `str` | Complete file under review |
| `code_diff` | `str` | Unified diff |
| `existing_comments` | `list` | Agent's prior comments |
| `step_number` / `max_steps` | `int` | Step progress |
| `available_files` | `list` | Files available for inspection (hard task) |

---

## Tasks (3 Difficulty Tiers)

| Task | Domain | Real Bugs | Files | Traps | Semantic Check |
|------|--------|:---------:|:-----:|:-----:|:--------------:|
| **easy** | List processing | 3 | 1 | β€” | β€” |
| **medium** | Web API handler | 4 | 1 | β€” | β€” |
| **hard** | Async crypto service | 6 | 3 | 1 red herring + 2 adversarial comments | βœ“ explanation_tiers |

### Task Details
- **Easy:** Off-by-one IndexError, null safety check, assignment-in-conditional syntax bug
- **Medium:** SQL injection, XSS, IDOR, hardcoded API secret
- **Hard:** Unsafe YAML deserialization (RCE), ECB cipher mode, async generator leak, race condition on shared dict, hardcoded secret key fallback, sync I/O blocking event loop β€” plus a red herring `try-except: pass` in a retry loop

---

## Reward Function

| Condition | Reward |
|---|---:|
| Correct bug match (Β±5 lines, severity+category) | +0.15 to +0.30 |
| Severity / category match bonus | +0.05 |
| **Semantic keyword miss** (hard task) | **βˆ’0.10** |
| **Confidence Calibration** (if confidence > 80%) | **+0.05 (correct) or βˆ’0.10 (wrong)** |
| Duplicate comment | βˆ’0.05 |
| False positive | βˆ’0.10 |
| Red herring flagged | βˆ’0.20 |
| `done` action | Final weighted F1 grader score |
| Efficiency bonus (fast + high score) | +0.10 |

**Grader:** Weighted F1 with strict 1-to-1 bug-to-comment matching.
Severity weights: `critical=3, major=2, minor=1, nit=0.5`.
False positives are weighted by their assigned severity to penalize spamming.
All scores deterministic and reproducible.

---

## Baseline Scores (Latest Results)

Includes Telemetric Confidence Scoring.

### πŸ† HUGGING FACE NATIVE SERVERLESS (Final Production Phase)
Native inference parsing successfully verified directly over `https://router.huggingface.co/v1`. DeepSeek-V3 completely dominated the native test group, surgically identifying every web vulnerability in the medium test environment to achieve a mathematically perfect 0.999 limit ceiling.

| Native Model Identifier | Environment | Easy F1 | Medium F1 | Hard F1 | **Avg F1** | Avg Conf. |
| :---------------------- | :---------- | :------ | :-------- | :------ | :--------- | :-------- |
| `deepseek-ai/DeepSeek-V3` | ✨ **HuggingFace** | 0.667 | **0.999** | 0.564 | **0.743** | 97% |
| `Qwen/Qwen2.5-72B-Instruct` | ✨ **HuggingFace** | 0.200 | 0.588 | 0.286 | **0.358** | 95% |
| `meta-llama/Meta-Llama-3-8B-Instruct` | ✨ **HuggingFace** | 0.429 | 0.001 | 0.001 | **0.144** | 96% |
| `meta-llama/Llama-3.3-70B-Instruct` | ❌ Rate Limited | - | - | - | **-** | - |
| `mistralai/Mixtral-8x7B-Instruct-v0.1` | ❌ Model Unsupported | - | - | - | **-** | - |

### 🌐 POST-SUBMISSION OPENROUTER BENCHMARKS
Final stress test verification leveraging OpenRouter API failover.

| Native Model Identifier | Environment | Easy F1 | Medium F1 | Hard F1 | **Avg F1** | Avg Conf. |
| :---------------------- | :---------- | :------ | :-------- | :------ | :--------- | :-------- |
| `deepseek-ai/DeepSeek-V3` | πŸš€ **OpenRouter** | 0.750 | 0.667 | 0.720 | **0.712** | 92% |
| `openai/gpt-4o-mini` | πŸš€ **OpenRouter** | 0.833 | 0.667 | 0.581 | **0.694** | 90% |
| `meta-llama/llama-3.3-70b-instruct` | πŸš€ **OpenRouter** | 0.500 | 0.833 | 0.545 | **0.626** | 94% |
| `qwen/qwen-2.5-72b-instruct` | πŸš€ **OpenRouter** | 0.800 | 0.556 | 0.500 | **0.619** | 97% |
| `mistralai/mistral-small-3.1-24b` | πŸš€ **OpenRouter** | 0.001 | 0.001 | 0.999 | **0.334** | 10% |

### 🧠 Performance Analysis: Why Models Succeed or Fail
Our deterministic grading environment reveals deep behaviors not captured by standard multiple-choice benchmarks:

- πŸ₯‡ **DeepSeek-V3 (The Winner):** Dominated because of superior **confidence calibration** and **semantic reasoning**. Unlike other models, DeepSeek doesn't just guess. When faced with the adversarial "Red Herring" (`try...except: pass` inside a backoff loop), its confidence drops, allowing it to bypass the trap entirely. It correctly uses multi-step logic to deduce *why* code is conceptually flawed rather than just syntactically incorrect.
- πŸ₯ˆ **Qwen-2.5-72B:** Highly capable at identifying localized syntax and logic errors in the Easy and Medium environments. However, it suffered in the Hard task, demonstrating **limitations in long-context, cross-file reasoning**. It often failed to correctly track how keys generated in `config_loader.py` were insecurely consumed in `crypto_service.py`.
- πŸ₯‰ **Llama-3.3-70B (The Overconfident Guesser):** Suffered mathematically due to **overconfidence syndrome**. The environment heavily penalizes false positives submitted with `>80%` confidence. Llama consistently flagged totally secure, verified code blocks as "Critical Vulnerabilities" with `95%` confidence, causing its F1 score to crash dynamically. It could not differentiate real bugs from the adversarial comment injections.
- πŸ“‰ **Smaller/Local Models (Mixtral, Meta-Llama-8B, Gemma):** Generally failed either due to **JSON parsing collapse** (outputting conversational text or reasoning tags instead of strict operation schemas) or by reaching maximum timeout limits when scanning larger codeblocks.

See [`FINDINGS_PAPER.md`](./FINDINGS_PAPER.md) for full analysis.

---

## Setup & Usage

### Prerequisites
```bash
pip install -r code-review-env/requirements.txt
```

### Run Server
```bash
cd code-review-env
uvicorn server:app --host 0.0.0.0 --port 7860
```

### Docker
```bash
cd code-review-env
docker build -t code-review-env .
docker run -p 7860:7860 code-review-env
```

### Run Inference

The inference script reads these environment variables:
- `API_BASE_URL` β€” The API endpoint for the LLM (default: `https://router.huggingface.co/v1`)
- `MODEL_NAME` β€” The model identifier (default: `Qwen/Qwen2.5-72B-Instruct`)
- `HF_TOKEN` β€” Your Hugging Face / API key (**required**)
- `ENV_BASE_URL` β€” Environment server URL (default: `http://127.0.0.1:7860`)

```bash
# LLM mode (requires API key)
API_BASE_URL=https://router.huggingface.co/v1 \
MODEL_NAME=Qwen/Qwen2.5-72B-Instruct \
HF_TOKEN=<your-token> \
python inference.py

# Benchmark mode (deterministic, no LLM needed)
REVIEW_STRATEGY=benchmark TASK_IDS=easy,medium,hard \
python inference.py
```

### Run Tests
```bash
python -m pytest code-review-env/tests -v
```

---

## Project Structure

```
code-reviewer-v2/
β”œβ”€β”€ server.py                    # Root FastAPI entrypoint (delegates to impl)
β”œβ”€β”€ inference.py                 # Root inference shim (delegates to impl)
β”œβ”€β”€ openenv.yaml                 # OpenEnv specification manifest
β”œβ”€β”€ Dockerfile                   # Container build definition
β”œβ”€β”€ pyproject.toml               # Project config + pytest settings
β”œβ”€β”€ requirements.txt             # Python dependencies
β”œβ”€β”€ README.md                    # This file
β”œβ”€β”€ FINDINGS_PAPER.md            # Academic findings paper
β”œβ”€β”€ ARCHITECTURE_BLUEPRINT.md    # Technical architecture docs
β”œβ”€β”€ AUDIT_RESULTS.md             # Full audit & compliance results
β”œβ”€β”€ REQUIREMENTS_CHECKLIST.md    # OpenEnv requirements checklist
β”œβ”€β”€ updatess.txt                 # Benchmark progression & change log
β”œβ”€β”€ lgos-complate.txt            # Benchmark log (Run 1 β€” 5 models)
β”œβ”€β”€ logs-2m.txt                  # Benchmark log (Run 2 β€” 6 models)
β”œβ”€β”€ logs-3.txt                   # Benchmark log (Run 3 β€” 6 models, latest)
β”œβ”€β”€ code-review-env/
β”‚   β”œβ”€β”€ server.py                # FastAPI server with /reset, /step, /state, /health
β”‚   β”œβ”€β”€ inference.py             # Full LLM inference engine + benchmark mode
β”‚   β”œβ”€β”€ openenv.yaml             # OpenEnv spec (impl copy)
β”‚   β”œβ”€β”€ Dockerfile               # Impl Dockerfile
β”‚   β”œβ”€β”€ requirements.txt         # Impl dependencies
β”‚   β”œβ”€β”€ env/
β”‚   β”‚   β”œβ”€β”€ environment.py       # Core environment engine
β”‚   β”‚   β”œβ”€β”€ reward_engine.py     # Shaped reward computation
β”‚   β”‚   β”œβ”€β”€ state_manager.py     # Episode state tracking
β”‚   β”‚   β”œβ”€β”€ models.py            # Pydantic data schemas
β”‚   β”‚   β”œβ”€β”€ graders/
β”‚   β”‚   β”‚   β”œβ”€β”€ base_grader.py   # Weighted F1 with semantic gates
β”‚   β”‚   β”‚   β”œβ”€β”€ grader_easy.py   # Easy task grader
β”‚   β”‚   β”‚   β”œβ”€β”€ grader_medium.py # Medium task grader
β”‚   β”‚   β”‚   └── grader_hard.py   # Hard task grader (multi-file)
β”‚   β”‚   └── tasks/
β”‚   β”‚       β”œβ”€β”€ task_easy.py     # 3 runtime logic bugs
β”‚   β”‚       β”œβ”€β”€ task_medium.py   # 4 security vulnerabilities
β”‚   β”‚       └── task_hard.py     # 6 bugs across 3 files + 1 red herring
β”‚   └── tests/                   # 70+ automated tests
└── server/                      # Alternate ASGI entrypoint
```

## Validation

```bash
openenv validate
```

- `pytest` β†’ **70 passed**
- `openenv validate` β†’ **Passes**
- All live endpoints return HTTP 200
- Dockerfile builds and runs cleanly
- Inference completes in <20 minutes on vcpu=2, memory=8gb