Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
7
7
language
stringclasses
6 values
code_snippet
stringlengths
4
429
review_comment
stringlengths
34
220
comment_type
stringclasses
9 values
severity
stringclasses
4 values
is_blocking
bool
2 classes
suggested_fix
stringlengths
0
473
rationale
stringlengths
34
192
cr_0000
python
items = [] for i in range(len(data)): items.append(data[i] * 2)
Use a list comprehension instead of a manual loop with index. It's more idiomatic Python and faster.
style
minor
false
items = [x * 2 for x in data]
List comprehensions are the idiomatic Python pattern and are compiled to faster bytecode than equivalent for-loops with append.
cr_0001
javascript
async function publishEvent(data) { db.events.publish(data); // forgot await return { success: true }; }
Missing `await` before `db.events.publish(data)`. The event publish runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function publishEvent(data) { await db.events.publish(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0002
python
with contextlib.suppress(Exception): risky_operation()
Suppressing all `Exception` types silently hides bugs. Suppress only the specific exception you expect.
bug
critical
true
Suppressing all `Exception` types silently hides bugs. Suppress only the specific exception you expect.
cr_0003
javascript
if (responseTime > 25) { throw new Error('Timeout'); }
Suggestion: Magic number `25` — what is it? Define `const PAGE_SIZE = 25;` (pagination page size) and reference it by name.
readability
minor
false
const PAGE_SIZE = 25; # then use the named constant
Magic numbers have no self-evident meaning. Named constants communicate intent, make global changes easy, and reduce the cognitive load of reading.
cr_0004
javascript
app.get('/documents', async (req, res) => { const items = await db.documents.findAll(); res.json(items); });
No pagination on `/documents`. This returns the full document collection on every request. Add `limit`/`offset` (or cursor) parameters and cap the max page size.
design
major
true
app.get('/documents', async (req, res) => { const limit = Math.min(parseInt(req.query.limit) || 20, 100); const offset = parseInt(req.query.offset) || 0; const items = await db.documents.findAll({ limit, offset }); res.json({ data: items, limit, offset }); });
Unbounded collection endpoints are a latent DoS vector. As the table grows, every request can trigger OOM errors and multi-second queries.
cr_0005
typescript
app.use((err: Error, req: Request, res: Response, next: NextFunction) => { res.status(500).json({ error: err.message, stack: err.stack }); });
Error handler leaks the stack trace to clients. In production, return a generic error message and log the details server-side.
security
critical
true
app.use((err: Error, req: Request, res: Response, next: NextFunction) => { logger.error('Unhandled error', { err, path: req.path }); const isProd = process.env.NODE_ENV === 'production'; res.status(500).json({ error: isProd ? 'Internal Server Error' : err.message, }); });
Stack traces reveal file paths, library versions, and internal logic, giving attackers a map of the system. Always suppress them in production API responses.
cr_0006
typescript
let map = new Map(); map.set('key', value); // map type is Map<unknown, unknown>
Map inferred as `Map<unknown, unknown>`. Provide type args: `new Map<string, ValueType>()`.
style
minor
false
Map inferred as `Map<unknown, unknown>`. Provide type args: `new Map<string, ValueType>()`.
cr_0007
typescript
async function processEvent(data) { repository.process(data); // forgot await return { success: true }; }
Missing `await` before `repository.process(data)`. The event process runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function processEvent(data) { await repository.process(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0008
go
func (s *NotificationService) Notification(ctx context.Context, id string) *Notification { row, _ := s.db.QueryRow(ctx, "SELECT * FROM notifications WHERE id=$1", id) var m Notification row.Scan(&m) return &m }
Important: Both errors from `QueryRow` and `Scan` are discarded. If the record doesn't exist, `m` will be a zero-value `Notification` returned as if it were valid.
bug
critical
true
func (s *NotificationService) GetNotification(ctx context.Context, id string) (*Notification, error) { var m Notification err := s.db.QueryRowContext(ctx, "SELECT * FROM notifications WHERE id=$1", id).Scan(&m) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } return &m, err }
Discarding QueryRow/Scan errors causes silent zero-value returns. The caller cannot distinguish 'found' from 'not found' or DB error.
cr_0009
python
class InventoryService: def __init__(self): self.db = PostgreSQLDatabase(host='prod-db', port=5432) self.mailer = SMTPMailer(host='smtp.prod.com')
`InventoryService` instantiates its own DB and mailer in `__init__`. This hard-codes production credentials and makes unit testing impossible. Inject these as constructor parameters.
design
major
true
class InventoryService: def __init__(self, db: Database, mailer: Mailer): self.db = db self.mailer = mailer
Hard-coded dependencies in constructors violate Dependency Inversion. They prevent test isolation (can't swap a real DB for a mock) and require code changes to change config.
cr_0010
javascript
async function listInvoice(data) { db.invoices.list(data); // forgot await return { success: true }; }
Missing `await` before `db.invoices.list(data)`. The invoice list runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function listInvoice(data) { await db.invoices.list(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0011
python
def get_items(): items = cache.get('items') if items is None: items = db.fetch_items() cache.set('items', items) return items
No TTL set on the cache entry. Stale data will be served indefinitely if items change. Pass an explicit TTL.
bug
critical
true
CACHE_TTL = 300 # 5 minutes def get_items(): items = cache.get('items') if items is None: items = db.fetch_items() cache.set('items', items, timeout=CACHE_TTL) return items
Cache entries without TTL can serve stale data forever after an underlying update, leading to correctness bugs.
cr_0012
java
public class Job { public String id; public String name; public int count; }
`Job` has mutable public fields. Make it immutable: use `final` fields, a constructor, and no setters. Or use a Java record.
design
major
true
public record Job(String id, String name, int count) {}
Mutable value objects can be modified by any holder, causing subtle state corruption bugs. Records or final-field classes guarantee immutability.
cr_0013
java
public class InventoryService { private final ProductRepository repo = new ProductRepositoryImpl(); private final EmailService mailer = new SendGridMailer(); }
Question: are you sure about this? Direct instantiation of `ProductRepositoryImpl` and `SendGridMailer` hard-codes concrete types. Use constructor injection and program to interfaces.
design
major
true
public class InventoryService { private final ProductRepository repo; private final EmailService mailer; public InventoryService(ProductRepository repo, EmailService mailer) { this.repo = repo; this.mailer = mailer; } }
Instantiating concrete types inside a class prevents substitution for testing or configuration. Constructor injection with interfaces enables mocking and IoC container wiring.
cr_0014
go
sync.Mutex{} // passed by value
If a `Mutex` is copied (passed by value), the copy has its own independent lock. Always use a pointer to `Mutex` or embed it in a struct.
bug
critical
true
If a `Mutex` is copied (passed by value), the copy has its own independent lock. Always use a pointer to `Mutex` or embed it in a struct.
cr_0015
python
len(lst) > 0
Use `if lst:` instead of `if len(lst) > 0:`. Empty sequences are falsy in Python.
nitpick
nitpick
false
bool(lst) or `if lst:`
Use `if lst:` instead of `if len(lst) > 0:`. Empty sequences are falsy in Python.
cr_0016
java
public void getNotification(NotificationData data) { try { service.get(data); } catch (Exception e) { // ignore } }
Empty catch block ignores all exceptions. If `service.get` fails, the caller has no idea. Log and re-throw, or propagate the exception.
bug
major
true
public void getNotification(NotificationData data) { try { service.get(data); } catch (NotificationException e) { log.error("Failed to get notification: {}", e.getMessage(), e); throw new ServiceException("get failed", e); } }
Swallowing exceptions without logging makes production incidents undiagnosable. Always log before suppressing.
cr_0017
typescript
async function fetchUser(id: string): Promise<User> { const res = await fetch(`/api/users/${id}`); return res.json(); }
No error handling: network errors reject the promise silently, and non-2xx responses are parsed as JSON regardless.
bug
major
true
async function fetchUser(id: string): Promise<User> { const res = await fetch(`/api/users/${id}`); if (!res.ok) throw new Error(`HTTP ${res.status} fetching user ${id}`); return res.json() as User; }
Fetch only rejects on network failure. HTTP 4xx/5xx responses resolve normally. Without the `res.ok` check, error responses are misinterpreted as valid data.
cr_0018
javascript
async function authenticate(data) { db.save(data); // missing await return { success: true }; }
Missing `await` before `db.save(data)`. The save runs asynchronously and errors are silently dropped. The function returns before the save completes.
bug
critical
true
async function authenticate(data) { await db.save(data); return { success: true }; }
Un-awaited promises run fire-and-forget. Any errors they throw are unhandled rejections and the return value races with the actual completion.
cr_0019
typescript
async function fetchProduct(id: string): Promise<Product> { const res = await fetch(`/api/products/${id}`); return res.json(); }
Question: are you sure about this? No error handling: network errors reject the promise silently, and non-2xx responses are parsed as JSON regardless.
bug
major
true
async function fetchProduct(id: string): Promise<Product> { const res = await fetch(`/api/products/${id}`); if (!res.ok) throw new Error(`HTTP ${res.status} fetching product ${id}`); return res.json() as Product; }
Fetch only rejects on network failure. HTTP 4xx/5xx responses resolve normally. Without the `res.ok` check, error responses are misinterpreted as valid data.
cr_0020
javascript
async function validateEvent(data) { db.events.validate(data); // forgot await return { success: true }; }
Missing `await` before `db.events.validate(data)`. The event validate runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function validateEvent(data) { await db.events.validate(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0021
typescript
async function createNotification(data) { repository.create(data); // forgot await return { success: true }; }
Missing `await` before `repository.create(data)`. The notification create runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function createNotification(data) { await repository.create(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0022
python
def process(data: list) -> list: total = len(data) # never used return [item for item in data if item.active]
Variable `total` is assigned but never used. Remove it to avoid confusion.
style
nitpick
false
def process(data: list) -> list: return [item for item in data if item.active]
Unused variables are noise — readers wonder if it's a bug (forgot to use it) or intentional (left from a refactor).
cr_0023
python
def delete_session(data): try: return service.delete(data) except Exception: pass # silent
Exception in `delete_session` is swallowed silently. At minimum log it; ideally re-raise as a domain exception.
bug
major
true
def delete_session(data): try: return service.delete(data) except SpecificError as e: logger.error('delete_session failed: %s', e) raise SessionServiceError(str(e)) from e
Silent exception swallowing hides bugs, makes debugging impossible, and leaves the system in unknown state.
cr_0024
python
def create_report(data): try: return service.create(data) except Exception: pass # silent
Exception in `create_report` is swallowed silently. At minimum log it; ideally re-raise as a domain exception.
bug
major
true
def create_report(data): try: return service.create(data) except SpecificError as e: logger.error('create_report failed: %s', e) raise ReportServiceError(str(e)) from e
Silent exception swallowing hides bugs, makes debugging impossible, and leaves the system in unknown state.
cr_0025
python
def delete_report(data): try: return service.delete(data) except Exception: pass # silent
Exception in `delete_report` is swallowed silently. At minimum log it; ideally re-raise as a domain exception.
bug
major
true
def delete_report(data): try: return service.delete(data) except SpecificError as e: logger.error('delete_report failed: %s', e) raise ReportServiceError(str(e)) from e
Silent exception swallowing hides bugs, makes debugging impossible, and leaves the system in unknown state.
cr_0026
python
df['column'] = df['column'].apply(lambda x: x.strip())
`.apply(lambda x: x.strip())` is slow for string operations. Use `df['column'].str.strip()` for vectorized pandas string methods.
performance
major
true
`.apply(lambda x: x.strip())` is slow for string operations. Use `df['column'].str.strip()` for vectorized pandas string methods.
cr_0027
javascript
async function processInvoice(data) { db.invoices.process(data); // forgot await return { success: true }; }
Missing `await` before `db.invoices.process(data)`. The invoice process runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function processInvoice(data) { await db.invoices.process(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0028
rust
fn main() { let args: Vec<String> = std::env::args().collect(); println!("Running with {} args", args.len()); // process... }
No usage of `args[0]` (program name) or validation that required args are present. Add a check before indexing.
bug
critical
true
fn main() { let args: Vec<String> = std::env::args().collect(); if args.len() < 2 { eprintln!("Usage: {} <input-file>", args[0]); std::process::exit(1); } let input_path = &args[1]; // process... }
Accessing `args[n]` without length checks panics when not enough arguments are supplied.
cr_0029
go
func (s *MonitoringService) trigger_alert(ctx context.Context, input Input) (Output, error) { return s.impl.trigger_alert(ctx, input) }
No structured logging in `trigger_alert`. Add `slog.InfoContext(ctx, "trigger_alert", "input_id", input.ID)` at entry and a duration log on exit for traceability.
design
minor
false
func (s *MonitoringService) trigger_alert(ctx context.Context, input Input) (Output, error) { slog.InfoContext(ctx, "trigger_alert", "input_id", input.ID) start := time.Now() out, err := s.impl.trigger_alert(ctx, input) slog.InfoContext(ctx, "trigger_alert done", "duration_ms", time.Since(start).Millise...
Structured log entries with context propagation enable tracing across distributed systems and make debugging production incidents dramatically faster.
cr_0030
typescript
async function deleteUser(data) { repository.delete(data); // forgot await return { success: true }; }
Missing `await` before `repository.delete(data)`. The user delete runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function deleteUser(data) { await repository.delete(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0031
python
not len(lst)
Use `not lst` instead of `not len(lst)` — cleaner and avoids the redundant len call.
nitpick
nitpick
false
not lst
Use `not lst` instead of `not len(lst)` — cleaner and avoids the redundant len call.
cr_0032
javascript
async function deleteReport(data) { db.reports.delete(data); // forgot await return { success: true }; }
Missing `await` before `db.reports.delete(data)`. The report delete runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function deleteReport(data) { await db.reports.delete(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0033
typescript
interface Props extends React.HTMLAttributes<HTMLDivElement> {}
Extending from HTMLAttributes exposes all ~200 HTML div attributes in your component's props interface. Be explicit about which HTML attributes you forward.
design
major
true
Extending from HTMLAttributes exposes all ~200 HTML div attributes in your component's props interface. Be explicit about which HTML attributes you forward.
cr_0034
typescript
function index_document(data: any, options: any): any { return processor.run(data, options); }
All parameters typed as `any`. Define `DocumentData`, `DocumentOptions`, and `DocumentResult` interfaces and use them here.
style
minor
false
function index_document(data: DocumentData, options: DocumentOptions): DocumentResult { return processor.run(data, options); }
`any` disables TypeScript's type checker for these parameters. Every `any` is a potential runtime error that the compiler won't catch.
cr_0035
python
# Hard-coded: will break in dev/staging and expose secrets db_url = "postgresql://prod-user:prod-pass@prod-db.example.com:5432/app"
Hard-coded `DB_URL` contains a production value. This will be committed to source control, break in other environments, and expose credentials. Use an environment variable.
security
critical
true
db_url = os.environ['DB_URL']
Credentials and environment-specific URLs in source code are a security and operational risk — they can't be rotated, break across environments, and are exposed in git history.
cr_0036
java
@GetMapping("/documents") public List<Document> listDocuments() { return repository.findAll(); }
No pagination on `/documents`. This returns the full document collection on every request. Add `limit`/`offset` (or cursor) parameters and cap the max page size.
design
major
true
@GetMapping("/documents") public Page<Document> listDocuments(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) { return repository.findAll(PageRequest.of(page, Math.min(size, 100))); }
Unbounded collection endpoints are a latent DoS vector. As the table grows, every request can trigger OOM errors and multi-second queries.
cr_0037
java
public void updateOrder(OrderData data) { try { service.update(data); } catch (Exception e) { // ignore } }
Empty catch block ignores all exceptions. If `service.update` fails, the caller has no idea. Log and re-throw, or propagate the exception.
bug
major
true
public void updateOrder(OrderData data) { try { service.update(data); } catch (OrderException e) { log.error("Failed to update order: {}", e.getMessage(), e); throw new ServiceException("update failed", e); } }
Swallowing exceptions without logging makes production incidents undiagnosable. Always log before suppressing.
cr_0038
typescript
async function deleteSession(data) { repository.delete(data); // forgot await return { success: true }; }
Missing `await` before `repository.delete(data)`. The session delete runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function deleteSession(data) { await repository.delete(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0039
python
# uses literal 3 directly if response_time > 3: raise TimeoutError()
Nit: Magic number `3` — what is it? Define `MAX_RETRIES = 3` (maximum retry count for transient errors) and reference it by name.
readability
minor
false
MAX_RETRIES = 3 # then use the named constant
Magic numbers have no self-evident meaning. Named constants communicate intent, make global changes easy, and reduce the cognitive load of reading.
cr_0040
javascript
async function publishAuditLog(data) { db.audit_logs.publish(data); // forgot await return { success: true }; }
Missing `await` before `db.audit_logs.publish(data)`. The audit_log publish runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function publishAuditLog(data) { await db.audit_logs.publish(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0041
javascript
function BigComponent() { // 300+ lines of JSX and handlers }
This component is 300+ lines. Extract logical sections into smaller sub-components to improve readability and testability.
design
minor
false
// Split into: BigComponent, BigComponentHeader, BigComponentBody, etc.
Large components are hard to test in isolation, cause merge conflicts, and hide logic relationships.
cr_0042
typescript
const API_VERSION = 'v2';
API version constant with no explanation. Add: when v2 was introduced, what changed from v1, and when to use v1 vs v2.
documentation
minor
false
API version constant with no explanation. Add: when v2 was introduced, what changed from v1, and when to use v1 vs v2.
cr_0043
python
import os import os # duplicate
Duplicate import `os`. Remove one.
style
nitpick
false
Duplicate import `os`. Remove one.
cr_0044
python
events = Event.objects.all() for item in events: print(item.metadata.all())
Nit: N+1 query: loading all `events` then fetching `metadata` for each in a loop executes N additional queries. Use `select_related` or `prefetch_related('metadata')` to batch the join.
performance
major
true
events = Event.objects.prefetch_related('metadata').all() for item in events: print(item.metadata.all()) # now uses cached prefetch
With N items, an N+1 pattern executes 1 + N SQL queries. At N=1000, that's 1001 round-trips vs 2 with prefetch.
cr_0045
python
def parse_date(...): return datetime.strptime(s, '%Y-%m-%d')
No tests for `parse_date`. Add cases for typical input, boundary values (empty string, zero, negative), and invalid input.
testing
minor
false
# test cases: normal, boundary, invalid assert parse_date(normal) == expected assert parse_date(empty) == edge_result assert parse_date(invalid) raises/returns error
Utility functions without tests are high-risk: they're refactored freely and silent regressions accumulate.
cr_0046
javascript
app.get('/sessions', async (req, res) => { const items = await db.sessions.findAll(); res.json(items); });
No pagination on `/sessions`. This returns the full session collection on every request. Add `limit`/`offset` (or cursor) parameters and cap the max page size.
design
major
true
app.get('/sessions', async (req, res) => { const limit = Math.min(parseInt(req.query.limit) || 20, 100); const offset = parseInt(req.query.offset) || 0; const items = await db.sessions.findAll({ limit, offset }); res.json({ data: items, limit, offset }); });
Unbounded collection endpoints are a latent DoS vector. As the table grows, every request can trigger OOM errors and multi-second queries.
cr_0047
python
def create_invoice(name, email, phone, address, city, country, zip_code, role, status, metadata): ...
Minor: `create_invoice` takes 10 positional arguments. Group into a dataclass or a `CreateInvoiceRequest` object.
design
minor
false
from dataclasses import dataclass @dataclass class CreateInvoiceRequest: name: str email: str phone: str address: str city: str country: str zip_code: str role: str status: str metadata: dict def create_invoice(request: CreateInvoiceRequest): ...
Functions with many positional parameters are fragile (argument order matters) and create unreadable call sites. A data class is self-documenting and extensible.
cr_0048
javascript
const result = JSON.parse(JSON.stringify(obj));
Using `JSON.parse(JSON.stringify(...))` for deep clone is slow and loses non-JSON types. Use `structuredClone()` in modern JS.
performance
minor
false
Using `JSON.parse(JSON.stringify(...))` for deep clone is slow and loses non-JSON types. Use `structuredClone()` in modern JS.
cr_0049
python
# Constants MAX = 100 MIN = 0 STEP = 5
Constants without explanation. Add a comment describing the business context: what does MAX represent, in what unit, and why 100?
documentation
nitpick
false
Constants without explanation. Add a comment describing the business context: what does MAX represent, in what unit, and why 100?
cr_0050
typescript
async function getUser(data) { repository.get(data); // forgot await return { success: true }; }
Missing `await` before `repository.get(data)`. The user get runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function getUser(data) { await repository.get(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0051
typescript
async function validateReport(data) { repository.validate(data); // forgot await return { success: true }; }
Missing `await` before `repository.validate(data)`. The report validate runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function validateReport(data) { await repository.validate(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0052
python
def event_op(conn, id): q = 'SELECT * FROM ' + entities + ' WHERE name = \'' + name + '\'' return conn.execute(q)
SQL injection via string concatenation: `id` is interpolated directly into the query string. Use parameterized queries (`%s` placeholders) instead.
security
critical
true
def event_op(conn, id): return conn.execute('SELECT * FROM events WHERE id = %s', (id,))
String interpolation into SQL allows attackers to escape the query context and execute arbitrary SQL, including reading, modifying, or deleting data.
cr_0053
rust
/// # Example /// ``` /// let x = my_fn(42); /// ```
Doctest code is never compiled or run unless you add it to `cargo test`. Verify this example actually works with `cargo test --doc`.
documentation
nitpick
false
Doctest code is never compiled or run unless you add it to `cargo test`. Verify this example actually works with `cargo test --doc`.
cr_0054
java
public class Utils { private Utils() {} // 200 static helper methods }
Giant Utils class with 200 methods. Organize helpers into domain-specific classes like `DateUtils`, `StringUtils`, `FileUtils`.
design
major
true
Giant Utils class with 200 methods. Organize helpers into domain-specific classes like `DateUtils`, `StringUtils`, `FileUtils`.
cr_0055
typescript
async function publishProduct(data) { repository.publish(data); // forgot await return { success: true }; }
Missing `await` before `repository.publish(data)`. The product publish runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function publishProduct(data) { await repository.publish(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0056
python
SECRET_KEY = os.environ.get('SECRET_KEY', 'fallback-dev-key')
Fallback secret key means the app 'works' with a known weak key if the env var is missing. Raise an error instead of falling back.
security
major
true
Fallback secret key means the app 'works' with a known weak key if the env var is missing. Raise an error instead of falling back.
cr_0057
javascript
async function listTransaction(data) { db.transactions.list(data); // forgot await return { success: true }; }
Missing `await` before `db.transactions.list(data)`. The transaction list runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function listTransaction(data) { await db.transactions.list(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0058
javascript
async function deleteProduct(data) { db.products.delete(data); // forgot await return { success: true }; }
Missing `await` before `db.products.delete(data)`. The product delete runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function deleteProduct(data) { await db.products.delete(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0059
python
items = [] for i in range(len(data)): items.append(data[i] * 2)
Nit: use a list comprehension instead of a manual loop with index. it's more idiomatic python and faster.
style
nitpick
false
items = [x * 2 for x in data]
List comprehensions are the idiomatic Python pattern and are compiled to faster bytecode than equivalent for-loops with append.
cr_0060
javascript
import { useState, useEffect, useCallback, useMemo } from 'react'; // only useState used const [x, setX] = useState(0);
Unused imports increase compile time (slightly), add noise, and mislead readers about what this module depends on. Remove them.
style
nitpick
false
import { useState } from 'react'; const [x, setX] = useState(0);
Unused imports are a form of dead code. They confuse readers who wonder if the import is used somewhere indirectly, and they bloat the module's dependency surface.
cr_0061
rust
pub fn parse_config(input: &str) -> Result<Config, ParseError> {
Missing rustdoc. Add `# Errors` section explaining which parse failures produce which `ParseError` variants.
documentation
minor
false
Missing rustdoc. Add `# Errors` section explaining which parse failures produce which `ParseError` variants.
cr_0062
java
for (Integer i = 0; i < 1000; i++)
Boxing `int` as `Integer` in the loop causes 1000 autobox/unbox operations. Use primitive `int i = 0`.
performance
major
true
Boxing `int` as `Integer` in the loop causes 1000 autobox/unbox operations. Use primitive `int i = 0`.
cr_0063
typescript
function getUser(id: any): any { return db.find(id); }
Using `any` defeats TypeScript's type checking. Define proper types for the parameter and return value.
style
minor
false
async function getUser(id: string): Promise<User | null> { return db.find(id); }
`any` is a type-system escape hatch that silences all errors, including legitimate ones. Proper types prevent bugs at compile time.
cr_0064
typescript
async function validateTransaction(data) { repository.validate(data); // forgot await return { success: true }; }
Missing `await` before `repository.validate(data)`. The transaction validate runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function validateTransaction(data) { await repository.validate(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0065
python
s.upper() == s.upper()
Nit: comparing a string to itself with `.upper()` is always True. Did you mean to compare two different strings?
nitpick
nitpick
false
s.upper() == other.upper()
Nit: comparing a string to itself with `.upper()` is always True. Did you mean to compare two different strings?
cr_0066
typescript
async function getWebhook(data) { repository.get(data); // forgot await return { success: true }; }
Missing `await` before `repository.get(data)`. The webhook get runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function getWebhook(data) { await repository.get(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0067
java
/** * Processes a event. * @param input the event to process * @return the processed result */ public EventResult track_event(EventData input) { ... }
Javadoc documents the happy path only. Add `@throws` for the exceptions this method can raise and clarify what 'processed result' means.
documentation
minor
false
/** * Processes a event through validation and transformation. * * @param input non-null EventData with all required fields populated * @return EventResult with status COMPLETED on success * @throws EventValidationException if required fields are missing * @throws EventProcessingException if an internal error occ...
Without @throws, callers have no way to know which checked exceptions to handle without reading the implementation.
cr_0068
rust
pub struct Cache<K, V> {
No struct-level docs. Document: eviction policy (LRU? LFU? FIFO?), thread-safety guarantees, and whether keys require `Hash + Eq`.
documentation
nitpick
false
No struct-level docs. Document: eviction policy (LRU? LFU? FIFO?), thread-safety guarantees, and whether keys require `Hash + Eq`.
cr_0069
go
func Retry(fn func() error, n int, d time.Duration) error {
GoDoc missing. Start with `// Retry calls fn up to n times...` and document: whether d is fixed or exponential, what happens when n=0.
documentation
minor
false
GoDoc missing. Start with `// Retry calls fn up to n times...` and document: whether d is fixed or exponential, what happens when n=0.
cr_0070
python
@app.get('/orders') def list_orders(): return db.query(Order).all()
No pagination on `/orders`. This returns the full order collection on every request. Add `limit`/`offset` (or cursor) parameters and cap the max page size.
design
major
true
@app.get('/orders') def list_orders(limit: int = 20, offset: int = 0): return db.query(Order).offset(offset).limit(min(limit, 100)).all()
Unbounded collection endpoints are a latent DoS vector. As the table grows, every request can trigger OOM errors and multi-second queries.
cr_0071
java
public Report getReport(String id) { return repository.findById(id).get(); }
Suggestion: `.get()` on an `Optional` throws `NoSuchElementException` if the report with `id` doesn't exist. Use `.orElseThrow()` with a meaningful exception.
bug
major
true
public Report getReport(String id) { return repository.findById(id) .orElseThrow(() -> new ReportNotFoundException(id)); }
Optional.get() is a code smell in production code. orElseThrow provides a clear error type and message for callers.
cr_0072
javascript
async function validateReport(data) { db.reports.validate(data); // forgot await return { success: true }; }
Missing `await` before `db.reports.validate(data)`. The report validate runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function validateReport(data) { await db.reports.validate(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0073
go
func (s *InvoiceService) ListInvoice(ctx context.Context, id string) { result, _ := s.repo.List(ctx, id) s.process(result) }
Error from `s.repo.List` is discarded with `_`. Silent errors here mean `result` may be nil/zero-value, causing a nil dereference in `s.process`.
bug
critical
true
func (s *InvoiceService) ListInvoice(ctx context.Context, id string) error { result, err := s.repo.List(ctx, id) if err != nil { return fmt.Errorf("list invoice: %w", err) } return s.process(result) }
Discarding errors in Go is the single most common source of silent bugs. Always check errors, especially from I/O operations.
cr_0074
python
def create_session(data): if data: result = process(data) if result: save(result) return result else: return None else: return None
Deeply nested conditionals can be flattened with early returns. Return/raise at the guard checks to reduce nesting.
readability
minor
false
def create_session(data): if not data: return None result = process(data) if not result: return None save(result) return result
Early-return (guard clause) style reduces nesting depth from 3 levels to 1, making the happy path obvious at the bottom.
cr_0075
javascript
async function saveUser(user) { await db.users.insert(user); await emailService.sendWelcome(user.email); await analyticsService.track('user_created', user.id); await slackService.notify('#signups', user); }
`saveUser` has 4 responsibilities: persistence, email, analytics, and notifications. If Slack is down, the user save rolls back. Extract side effects into an event/queue pattern.
design
major
true
async function saveUser(user) { await db.users.insert(user); await eventBus.publish('user.created', user); // subscribers handle email, analytics, Slack }
Coupling all side effects in one transaction means a flaky notification service can roll back a DB write. Event-driven decoupling makes each step independent and retryable.
cr_0076
python
with open(path, 'wb') as f: f.write(pickle.dumps(data))
Storing data as pickle ties you to Python and makes the file unreadable in other systems. Use JSON or Parquet for interoperable serialization.
design
minor
false
Storing data as pickle ties you to Python and makes the file unreadable in other systems. Use JSON or Parquet for interoperable serialization.
cr_0077
python
class MessagingService: def send_message(self, data): result = self._process(data) return result
No metrics or tracing in `send_message`. For a service-level method, add a duration histogram and error counter so you can detect regressions in production.
design
minor
false
class MessagingService: def send_message(self, data): with metrics.timer('messagingservice.send_message'): try: result = self._process(data) metrics.increment('messagingservice.send_message.success') return result except Exception: ...
Without metrics, you can't distinguish a slow deploy from a traffic spike. Timer + error counter is the minimum useful observability for a service method.
cr_0078
rust
use serde_json::Value; fn process(v: Value) { ... }
Accepting `serde_json::Value` loses all type safety — you're back to dynamic typing. Define a typed struct and derive `Deserialize` instead.
design
major
true
Accepting `serde_json::Value` loses all type safety — you're back to dynamic typing. Define a typed struct and derive `Deserialize` instead.
cr_0079
typescript
async function validateNotification(data) { repository.validate(data); // forgot await return { success: true }; }
Missing `await` before `repository.validate(data)`. The notification validate runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function validateNotification(data) { await repository.validate(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0080
python
def parse_config(path: str) -> dict:
Missing docstring. Document: supported config formats, required keys, what happens if a required key is absent.
documentation
nitpick
false
Missing docstring. Document: supported config formats, required keys, what happens if a required key is absent.
cr_0081
python
def find_duplicates(lst): return [x for x in lst if lst.count(x) > 1]
`lst.count(x)` is O(n) and called for every element, making this O(n²). Use a `Counter` to find duplicates in O(n).
performance
minor
false
from collections import Counter def find_duplicates(lst): counts = Counter(lst) return [x for x, n in counts.items() if n > 1]
O(n²) list scanning is fine for small inputs but catastrophic for n > 10,000. Counter-based approach is O(n) time and space.
cr_0082
typescript
export const globalState = { user: null, cart: [], theme: 'light', notifications: [], }; // mutated directly everywhere
Mutable global state shared across the app is a maintenance nightmare. Use a state management solution (Redux, Zustand) with immutable updates, or split into smaller context providers.
design
major
true
// Use Zustand or Redux slice per domain: const useUserStore = create<UserState>(set => ({ user: null, setUser: (u) => set({ user: u }), })); const useCartStore = create<CartState>(...);
Direct mutation of global state makes it impossible to track where state changes originate, preventing time-travel debugging and causing cascading re-renders.
cr_0083
go
func process(items []Item) []Result { results := []Result{} for _, item := range items { results = append(results, transform(item)) } return results }
Pre-allocate the results slice with `make([]Result, 0, len(items))` to avoid repeated reallocations during append.
performance
minor
false
func process(items []Item) []Result { results := make([]Result, 0, len(items)) for _, item := range items { results = append(results, transform(item)) } return results }
Without a capacity hint, `append` doubles the backing array whenever it runs out of space. Pre-allocating avoids O(log n) re-allocations.
cr_0084
python
def read_data(path): f = open(path) return f.read()
File `f` is opened but never closed. Use a `with` statement to ensure the file descriptor is released even if an exception occurs.
bug
major
true
def read_data(path): with open(path) as f: return f.read()
Open file handles are OS resources. If not closed, they leak until GC runs, which can exhaust file descriptor limits.
cr_0085
go
log.Printf("User data: %v", user.PhoneNumber)
Important: Logging `user.PhoneNumber` (phone number) is a PII leak. Remove this log or replace with a non-sensitive identifier (e.g. user ID or masked value).
security
critical
true
log.Printf("Processing user: %s", user.ID)
Logging phone number violates GDPR/CCPA and exposes sensitive user data in log aggregation systems accessible to engineers and tooling.
cr_0086
typescript
const value = obj as any as TargetType;
Double-cast via `any` is a red flag — it bypasses TypeScript's type narrowing completely. If this is needed, add a runtime validation check (e.g., a type guard function).
style
major
true
function isTargetType(x: unknown): x is TargetType { return typeof x === 'object' && x !== null && 'requiredField' in x; } if (isTargetType(obj)) { // obj is TargetType here }
Double-casting is a sign that the type information is wrong at the source. A type guard expresses the runtime invariant explicitly and provides type narrowing without escaping the type system.
cr_0087
go
func (s *ProductService) CreateProduct(ctx context.Context, id string) { result, _ := s.repo.Create(ctx, id) s.process(result) }
Error from `s.repo.Create` is discarded with `_`. Silent errors here mean `result` may be nil/zero-value, causing a nil dereference in `s.process`.
bug
critical
true
func (s *ProductService) CreateProduct(ctx context.Context, id string) error { result, err := s.repo.Create(ctx, id) if err != nil { return fmt.Errorf("create product: %w", err) } return s.process(result) }
Discarding errors in Go is the single most common source of silent bugs. Always check errors, especially from I/O operations.
cr_0088
java
public void getInvoice(InvoiceData data) { try { service.get(data); } catch (Exception e) { // ignore } }
Empty catch block ignores all exceptions. If `service.get` fails, the caller has no idea. Log and re-throw, or propagate the exception.
bug
major
true
public void getInvoice(InvoiceData data) { try { service.get(data); } catch (InvoiceException e) { log.error("Failed to get invoice: {}", e.getMessage(), e); throw new ServiceException("get failed", e); } }
Swallowing exceptions without logging makes production incidents undiagnosable. Always log before suppressing.
cr_0089
typescript
function generate_report(data: any, options: any): any { return processor.run(data, options); }
All parameters typed as `any`. Define `ReportData`, `ReportOptions`, and `ReportResult` interfaces and use them here.
style
minor
false
function generate_report(data: ReportData, options: ReportOptions): ReportResult { return processor.run(data, options); }
`any` disables TypeScript's type checker for these parameters. Every `any` is a potential runtime error that the compiler won't catch.
cr_0090
javascript
const _ = require('lodash'); const fs = require('fs'); // only fs used fs.readFileSync(path);
Unused imports increase compile time (slightly), add noise, and mislead readers about what this module depends on. Remove them.
style
nitpick
false
const fs = require('fs'); fs.readFileSync(path);
Unused imports are a form of dead code. They confuse readers who wonder if the import is used somewhere indirectly, and they bloat the module's dependency surface.
cr_0091
python
class Singleton: _instance = None def __new__(cls): ... # no thread-safety
Singleton `__new__` is not thread-safe. Under concurrency, two threads can both pass the `_instance is None` check and create two instances. Use a lock.
bug
critical
true
Singleton `__new__` is not thread-safe. Under concurrency, two threads can both pass the `_instance is None` check and create two instances. Use a lock.
cr_0092
python
def divide(a, b): return a / b
Blocking: No guard against `b == 0`. This will raise `ZeroDivisionError` in production. Add a check or let callers pass validated inputs.
bug
critical
true
def divide(a, b): if b == 0: raise ValueError('Divisor cannot be zero') return a / b
Division by zero is a common runtime error that can crash the service if not handled at the boundary.
cr_0093
javascript
function render(invoice) { const { id, payment_method, ...rest } = invoice; // `id` and `payment_method` never referenced below return <Component data={rest} />; }
Important: Destructured `id` and `payment_method` are never used in the function body. Either use them or remove them from the destructuring.
style
nitpick
false
function render(invoice) { return <Component data={invoice} />; }
Unused destructured bindings create the impression they're needed, misleading reviewers and maintainers.
cr_0094
python
def session_op(conn, id): q = f"SELECT * FROM sessions WHERE id = '{id}'" return conn.execute(q)
SQL injection via f-string SQL interpolation: `id` is interpolated directly into the query string. Use parameterized queries (`%s` placeholders) instead.
security
critical
true
def session_op(conn, id): return conn.execute('SELECT * FROM sessions WHERE id = %s', (id,))
String interpolation into SQL allows attackers to escape the query context and execute arbitrary SQL, including reading, modifying, or deleting data.
cr_0095
javascript
async function deleteDocument(data) { db.documents.delete(data); // forgot await return { success: true }; }
Missing `await` before `db.documents.delete(data)`. The document delete runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function deleteDocument(data) { await db.documents.delete(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
cr_0096
python
def track_event(data): result = db.execute('events', data) return result
Question: are you sure about this? `db.execute` can raise `DatabaseError`. `track_event` has no try/except, so any DB failure propagates as an unhandled exception.
bug
major
true
def track_event(data): try: return db.execute('events', data) except DatabaseError as e: logger.error('track_event failed: %s', e) raise ServiceError(str(e)) from e
Uncaught DatabaseError in track_event will cause a 500 with a stack trace exposed to clients. Wrap and re-raise with a domain exception.
cr_0097
typescript
interface Config { host: string; port: number; debug: boolean; timeout: number; retries: number; logLevel: string; maxConnections: number; password: string; }
Config interface has 8 fields. Consider grouping into nested interfaces (e.g., `DatabaseConfig`, `LogConfig`) for clarity.
design
minor
false
interface DatabaseConfig { host: string; port: number; password: string; maxConnections: number; } interface Config { db: DatabaseConfig; debug: boolean; timeout: number; retries: number; logLevel: string; }
Flat interfaces with many fields mix concerns. Grouping improves IDE autocomplete and makes partial config passing easier.
cr_0098
python
def retry(fn, max_retries=3, backoff=1.0): pass
`retry` has no docstring/comment. Document: what it does (retries fn up to max_retries times with exponential backoff), parameter semantics, return value, and error behavior.
documentation
nitpick
false
# Doc: Retries `fn` up to `n` times with exponential backoff starting at `delay` seconds. # Returns the last result or raises the last exception.
Public utility functions without docs force every caller to read the implementation to understand behavior and edge cases.
cr_0099
javascript
async function publishDocument(data) { db.documents.publish(data); // forgot await return { success: true }; }
Missing `await` before `db.documents.publish(data)`. The document publish runs fire-and-forget — errors are swallowed and the return happens before the operation completes.
bug
critical
true
async function publishDocument(data) { await db.documents.publish(data); return { success: true }; }
Un-awaited async operations complete after the function returns, making error handling impossible and causing race conditions.
End of preview. Expand in Data Studio

synthetic-code-review-comments

A synthetic dataset of 1,150 realistic code review comments spanning 6 programming languages and 9 comment types. Each example pairs a code snippet with a concrete, actionable review comment, a suggested fix, and a rationale explaining the why behind the feedback.

Built to support training and evaluation of:

  • Code review automation models
  • Code quality classifiers
  • Developer tool assistants
  • LLM fine-tuning for code critique

Dataset Summary

Split Count
train 920
validation 115
test 115
Total 1,150

Schema

Each row has the following fields:

Field Type Description
id string Unique identifier (e.g. cr_0001)
language string Programming language (python, javascript, typescript, go, java, rust)
code_snippet string The code being reviewed (typically a function, method, or short block)
review_comment string The code review comment — actionable, specific, and reviewer-voiced
comment_type string Category (see below)
severity string critical, major, minor, or nitpick
is_blocking boolean True if this comment must be resolved before merge
suggested_fix string Proposed corrected code or approach (present in ~75% of rows)
rationale string Explanation of why the issue matters

Comment Types

Type Count % Description
bug 494 43% Correctness issues: crashes, logic errors, race conditions
design 172 15% Architecture, coupling, SRP violations
style 112 10% Convention, naming, code formatting
security 78 7% Injection, credential leakage, XSS, RCE
performance 67 6% O(n²) patterns, N+1 queries, resource waste
readability 62 5% Clarity, magic numbers, nested conditions
testing 60 5% Missing or weak test coverage
documentation 56 5% Missing or inadequate docs/comments
nitpick 49 4% Minor style preferences

Language Distribution

Language Count %
Python 285 25%
JavaScript 191 17%
TypeScript 186 16%
Go 158 14%
Java 135 12%
Rust 71 6%

Severity Distribution

Severity Count %
critical 373 32%
major 314 27%
minor 217 19%
nitpick 122 11%
(mixed) 124 11%

Sample

{
  "id": "cr_0042",
  "language": "python",
  "code_snippet": "def get_user(user_id):\n    users = db.query('SELECT * FROM users WHERE id = ' + str(user_id))\n    return users[0]",
  "review_comment": "This is a SQL injection vulnerability — `user_id` is concatenated directly into the query string. Use parameterized queries instead.",
  "comment_type": "security",
  "severity": "critical",
  "is_blocking": true,
  "suggested_fix": "def get_user(user_id):\n    users = db.query('SELECT * FROM users WHERE id = %s', (user_id,))\n    return users[0]",
  "rationale": "Unsanitized user input in SQL queries allows attackers to manipulate the query logic, potentially dumping or deleting data."
}
{
  "id": "cr_0187",
  "language": "go",
  "code_snippet": "var mu sync.Mutex\nvar counter int\n\nfunc increment() {\n    counter++\n}",
  "review_comment": "`increment` modifies `counter` without holding `mu`. This is a data race. Lock before read-modify-write.",
  "comment_type": "bug",
  "severity": "critical",
  "is_blocking": true,
  "suggested_fix": "func increment() {\n    mu.Lock()\n    defer mu.Unlock()\n    counter++\n}",
  "rationale": "Concurrent writes to a shared variable without a mutex cause undefined behavior. Go's race detector (`go test -race`) will catch this."
}

Generation Methodology

The dataset was generated synthetically by SalutefaceAAC using:

  1. Hand-authored templates — 200+ base templates per language covering the most common and impactful code review patterns
  2. Domain cross-product expansion — templates applied across 20 domain contexts (auth, billing, inventory, analytics, search, etc.) to generate realistic varied code snippets
  3. Reviewer voice variation — comments phrased in natural reviewer styles (neutral, prefix "Blocking:", "Nit:", "Suggestion:", etc.)
  4. Deduplication — MD5 hash on (code_snippet, review_comment) to remove identical content

All examples were authored to reflect real-world review patterns observed in open-source projects and engineering best practices documentation.

Quality Notes

  • No personal data: all code snippets are synthetic with no real credentials, emails, or PII in the content (examples that reference credentials do so as the subject of the review comment, not as actual secrets)
  • Validation: 0 errors across all required field checks, enum validations, and duplicate checks
  • Rationale coverage: 100% of rows have a rationale explaining the why
  • Fix coverage: ~75% of rows include a suggested_fix; documentation/nitpick rows sometimes omit it when the fix is implicit in the comment

Intended Use

✅ Training code review automation models
✅ Fine-tuning LLMs for developer tool assistants
✅ Evaluating code quality classifiers
✅ Research into automated code review systems
✅ Building code review comment suggestion features

⚠️ Not intended as a comprehensive security dataset — security examples are illustrative, not exhaustive
⚠️ Synthetic data — may not capture all edge cases of real code review diversity

License

Apache 2.0

Citation

@dataset{salutefaceaac2026codereviews,
  author    = {SalutefaceAAC},
  title     = {synthetic-code-review-comments},
  year      = {2026},
  publisher = {Hugging Face},
  url       = {https://huggingface.co/datasets/SalutefaceAAC/synthetic-code-review-comments}
}
Downloads last month
38