find-race-conditions

Detects race conditions in PHP code. Finds shared mutable state, check-then-act patterns, TOCTOU vulnerabilities, concurrent modification issues.

59 stars

Best use case

find-race-conditions is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Detects race conditions in PHP code. Finds shared mutable state, check-then-act patterns, TOCTOU vulnerabilities, concurrent modification issues.

Teams using find-race-conditions should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/find-race-conditions/SKILL.md --create-dirs "https://raw.githubusercontent.com/dykyi-roman/awesome-claude-code/main/skills/find-race-conditions/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/find-race-conditions/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How find-race-conditions Compares

Feature / Agentfind-race-conditionsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Detects race conditions in PHP code. Finds shared mutable state, check-then-act patterns, TOCTOU vulnerabilities, concurrent modification issues.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Race Condition Detection

Analyze PHP code for concurrency issues and race conditions.

## Detection Patterns

### 1. Check-Then-Act (TOCTOU)

```php
// BUG: Time-of-check to time-of-use
if (file_exists($path)) {
    $content = file_get_contents($path); // File may be deleted
}

// BUG: Check then modify
if (!$user->hasOrder()) {
    $order = new Order();
    $user->addOrder($order); // Another request may add order
}

// BUG: Inventory check-then-act
if ($product->getStock() >= $quantity) {
    $product->decreaseStock($quantity); // Race with other orders
}
```

### 2. Shared Mutable State

```php
// BUG: Static mutable property
class Counter {
    private static int $count = 0;

    public function increment(): void {
        self::$count++; // Not atomic
    }
}

// BUG: Shared cache without locking
class Cache {
    private array $data = [];

    public function getOrSet(string $key, callable $factory): mixed {
        if (!isset($this->data[$key])) {
            $this->data[$key] = $factory(); // May compute twice
        }
        return $this->data[$key];
    }
}
```

### 3. Read-Modify-Write Without Lock

```php
// BUG: Non-atomic increment
$counter = $redis->get('counter');
$redis->set('counter', $counter + 1); // Lost update

// BUG: Balance update
$balance = $account->getBalance();
$account->setBalance($balance - $amount); // Race condition

// FIXED: Use atomic operations
$redis->incr('counter');
```

### 4. File System Race Conditions

```php
// BUG: Directory creation race
if (!is_dir($path)) {
    mkdir($path); // Another process may create it
}

// BUG: File write race
$data = json_decode(file_get_contents($file));
$data['count']++;
file_put_contents($file, json_encode($data)); // Lost update
```

### 5. Database Race Conditions

```php
// BUG: No optimistic locking
$entity = $repository->find($id);
$entity->setStatus('processed');
$entityManager->flush(); // Another process may have changed it

// BUG: Unique constraint race
if (!$repository->findByEmail($email)) {
    $user = new User($email);
    $entityManager->persist($user); // Duplicate may be created
}
```

### 6. Session Race Conditions

```php
// BUG: Session data race
$cart = $_SESSION['cart'];
$cart[] = $newItem;
$_SESSION['cart'] = $cart; // Lost update with concurrent requests
```

## Grep Patterns

```bash
# Check-then-act patterns
Grep: "if\s*\(file_exists\([^)]+\)\)\s*\{[^}]*file_get_contents" --glob "**/*.php"

# Static mutable properties
Grep: "private static\s+(?!readonly)" --glob "**/*.php"

# Read-modify-write on Redis
Grep: "->get\([^)]+\)[^;]*\+[^;]*->set" --glob "**/*.php"

# Non-atomic increment
Grep: "\+\+|\-\-|self::\$\w+\s*\+=" --glob "**/*.php"
```

## Severity Classification

| Pattern | Severity |
|---------|----------|
| Financial data race | 🔴 Critical |
| Inventory TOCTOU | 🔴 Critical |
| Unique constraint race | 🟠 Major |
| File system race | 🟠 Major |
| Cache stampede | 🟡 Minor |
| Counter race | 🟡 Minor |

## Fixes

### Use Locks

```php
// Database lock
$connection->beginTransaction();
$entity = $repository->find($id, LockMode::PESSIMISTIC_WRITE);
$entity->process();
$connection->commit();
```

### Use Atomic Operations

```php
// Redis atomic increment
$redis->incr('counter');

// Database atomic update
$connection->executeStatement(
    'UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?',
    [$quantity, $productId, $quantity]
);
```

### Use Optimistic Locking

```php
#[Version]
private int $version;

// Will throw OptimisticLockException on conflict
```

## Output Format

```markdown
### Race Condition: [Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**Type:** [TOCTOU|Shared State|Read-Modify-Write|...]

**Issue:**
[Description of the race condition]

**Code:**
```php
// Problematic code
```

**Fix:**
```php
// Thread-safe version
```
```

Related Skills

trace-request-lifecycle

59
from dykyi-roman/awesome-claude-code

Traces full request lifecycle from Router through Middleware, Controller, UseCase, Repository to Response. Documents HTTP methods, routes, middleware stack, response codes, and error handling paths.

trace-data-transformation

59
from dykyi-roman/awesome-claude-code

Maps data transformation chains — Request DTO to Command to Entity to Response DTO. Identifies mappers, serializers, type conversions, and data loss points across layer boundaries.

find-type-issues

59
from dykyi-roman/awesome-claude-code

Detects type issues in PHP code. Finds implicit type coercion, mixed types in comparisons, unsafe casting, type mismatches in returns.

find-resource-leaks

59
from dykyi-roman/awesome-claude-code

Detects resource leaks in PHP code. Finds unclosed file handles, database connections not released, streams not freed, missing finally blocks, temporary files not cleaned.

find-null-pointer-issues

59
from dykyi-roman/awesome-claude-code

Detects null pointer issues in PHP code. Finds property/method access on null, missing null checks, nullable returns without handling, optional chaining gaps.

find-logic-errors

59
from dykyi-roman/awesome-claude-code

Detects logic errors in PHP code. Finds incorrect conditions, wrong operators, missing switch cases, inverted logic, short-circuit evaluation issues.

find-infinite-loops

59
from dykyi-roman/awesome-claude-code

Detects infinite loop risks in PHP code. Finds missing break conditions, incorrect loop variables, unbounded recursion, circular references.

find-exception-issues

59
from dykyi-roman/awesome-claude-code

Detects exception handling issues in PHP code. Finds swallowed exceptions, generic catches, missing exception handling, re-throwing without context, exception in finally.

find-boundary-issues

59
from dykyi-roman/awesome-claude-code

Detects boundary issues in PHP code. Finds array index out of bounds, empty collection access, off-by-one errors, integer overflow, string length issues.

bug-root-cause-finder

59
from dykyi-roman/awesome-claude-code

Root cause analysis methods for PHP bugs. Provides 5 Whys technique, fault tree analysis, git bisect guidance, and stack trace parsing.

yii-knowledge

59
from dykyi-roman/awesome-claude-code

Yii framework knowledge base. Provides Yii3 modular architecture, DDD integration, PSR-7/PSR-15 compliance, persistence, DI, security (RBAC, auth), event system (PSR-14), queue/jobs, infrastructure components (cache, rate limiter, HTTP client), testing, and antipatterns for Yii PHP projects.

troubleshooting-template

59
from dykyi-roman/awesome-claude-code

Generates troubleshooting guides and FAQ sections for PHP projects. Creates problem-solution documentation.