find-race-conditions

Detect race conditions in PHP code: find shared mutable state, check-then-act patterns, TOCTOU vulnerabilities, and issues from concurrent modifications.

Last repository push
GitHub Stars
109
Forks
26
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "find-race-conditions" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-566a3a796e106967730bc07fe25d941b50ef8f6423f9080828b3131d9eb5d229. Verify the upstream source and version against https://github.com/dykyi-roman/awesome-claude-code before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Detect race conditions in PHP code: find shared mutable state, check-then-act patterns, TOCTOU vulnerabilities, and issues from concurrent modifications.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Detects race conditions in PHP code. Finds shared mutable state, check-then-act patterns, TOCTOU vulnerabilities, concurrent modification issues.
Inputs and outputs
```markdown
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: find-race-conditions
description: Detects race conditions in PHP code. Finds shared mutable state, check-then-act patterns, TOCTOU vulnerabilities, concurrent modification issues.

Race Condition Detection

Analyze PHP code for concurrency issues and race conditions.

Detection Patterns

1. Check-Then-Act (TOCTOU)

// 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

// 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

// 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

// 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

// 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

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

Grep Patterns

# 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

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

Use Atomic Operations

// 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

#[Version]
private int $version;

// Will throw OptimisticLockException on conflict

Output Format

### 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:

// Thread-safe version

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 提供PHP竞态条件检测的完整解决方案
  • 覆盖多种常见竞态条件模式
  • 包含严重性分类和修复建议
Trigger Precision90/100

Highlights

  • 触发词精准完整,覆盖多种变体
  • 边界清晰,不易误触
Structure and Standards85/100

Areas to improve

  • 缺少When to Use章节 Reported severity: Minor

    文档结构缺少明确的When to Use使用场景说明

    Recommendation: 建议添加When to Use章节,说明何时使用此Skill

Execution Reliability80/100

Areas to improve

  • 缺少grep命令异常处理 Reported severity: Minor

    Grep Patterns部分缺少对命令执行失败的异常处理说明

    Recommendation: 建议添加对grep命令执行失败的异常处理说明

Highlights

  • 工具来源明确,参数正确
  • 覆盖主要异常场景
  • 提供多种修复方案
Evidence Verifiability (mean of the first four)85/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.