find-infinite-loops

Detect infinite-loop risks in PHP code. Find missing exit conditions, incorrect loop variables, unbounded recursion, and cyclical references.

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-infinite-loops" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-e07b535f50b78c3ff5900730db40712700d4571b7e7e6bfae488d216a99ea0cd. 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 infinite-loop risks in PHP code. Find missing exit conditions, incorrect loop variables, unbounded recursion, and cyclical references.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Detects infinite loop risks in PHP code. Finds missing break conditions, incorrect loop variables, unbounded recursion, circular references.
Inputs and outputs
```markdown
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: find-infinite-loops
description: Detects infinite loop risks in PHP code. Finds missing break conditions, incorrect loop variables, unbounded recursion, circular references.

Infinite Loop Detection

Analyze PHP code for potential infinite loops and unbounded execution.

Detection Patterns

1. Missing Break Conditions

// BUG: No exit condition
while (true) {
    $item = $queue->pop();
    process($item);
    // No break when queue is empty
}

// BUG: Condition never changes
$running = true;
while ($running) {
    doWork();
    // $running never set to false
}

// BUG: Break inside nested condition
while ($items) {
    foreach ($items as $item) {
        if ($item->isDone()) {
            break; // Only breaks inner loop
        }
    }
}

2. Incorrect Loop Variable Modification

// BUG: Wrong variable incremented
for ($i = 0; $i < count($items); $j++) { // Should be $i++
    process($items[$i]);
}

// BUG: Variable modified in wrong direction
for ($i = 10; $i > 0; $i++) { // Should be $i--
    process($i);
}

// BUG: Loop variable reset
$i = 0;
while ($i < 10) {
    if ($condition) {
        $i = 0; // Resets counter
    }
    $i++;
}

3. Unbounded Recursion

// BUG: No base case
function factorial(int $n): int
{
    return $n * factorial($n - 1); // Never stops
}

// BUG: Base case unreachable
function traverse(Node $node): void
{
    $this->traverse($node->getNext()); // What if getNext returns self?
    // Missing: if ($node === null) return;
}

// BUG: Mutual recursion
function a($n) { return b($n); }
function b($n) { return a($n); } // Infinite cycle

4. Circular References

// BUG: Circular linked list traversal
while ($node !== null) {
    $node = $node->next; // What if list is circular?
}

// BUG: Object graph cycle
function serialize($obj, $visited = []): string
{
    foreach ($obj->getRelations() as $rel) {
        $result .= serialize($rel); // May revisit objects
    }
}

// FIXED:
function serialize($obj, array &$visited = []): string
{
    if (in_array($obj, $visited, true)) {
        return '[circular]';
    }
    $visited[] = $obj;
    // ...
}

5. Event/Listener Loops

// BUG: Event triggers itself
class UserUpdatedListener
{
    public function handle(UserUpdated $event): void
    {
        $user = $event->getUser();
        $user->touch(); // Triggers another UserUpdated event
    }
}

// BUG: Message queue requeue loop
public function handle(Message $message): void
{
    try {
        $this->process($message);
    } catch (Exception $e) {
        $this->queue->publish($message); // Requeues failed message infinitely
    }
}

6. Retry Without Limit

// BUG: Infinite retry
function fetch(string $url): string
{
    while (true) {
        try {
            return $this->httpClient->get($url);
        } catch (Exception $e) {
            sleep(1);
            // No max retries, infinite loop on persistent failure
        }
    }
}

// FIXED:
function fetch(string $url, int $maxRetries = 3): string
{
    $attempts = 0;
    while ($attempts < $maxRetries) {
        try {
            return $this->httpClient->get($url);
        } catch (Exception $e) {
            $attempts++;
            if ($attempts >= $maxRetries) {
                throw $e;
            }
            sleep(1);
        }
    }
}

7. Generator Infinite Yield

// BUG: Generator never ends
function allNumbers(): Generator
{
    $i = 0;
    while (true) {
        yield $i++;
        // Fine for generators, but consuming code may not limit
    }
}

// Usage BUG:
foreach (allNumbers() as $n) {
    echo $n; // Infinite loop
}

8. Database Pagination Without Limit

// BUG: Potentially infinite
$offset = 0;
while (true) {
    $batch = $repository->findBy([], null, 100, $offset);
    if (empty($batch)) {
        break;
    }
    process($batch);
    // Missing: $offset += 100;
}

Grep Patterns

# while(true) without break
Grep: "while\s*\(\s*true\s*\)" --glob "**/*.php"

# Recursion
Grep: "function\s+(\w+)\([^)]*\)[^{]*\{[^}]*\1\s*\(" --glob "**/*.php"

# for loop with wrong increment
Grep: "for\s*\([^;]+;\s*\$\w+\s*[<>]\s*[^;]+;\s*\$(?!\1)" --glob "**/*.php"

# while without modification
Grep: "while\s*\(\s*\$\w+\s*\)" --glob "**/*.php"

Severity Classification

Pattern Severity
Infinite retry without limit 🔴 Critical
Missing recursion base case 🔴 Critical
Wrong loop variable 🔴 Critical
Circular reference traversal 🟠 Major
Event self-triggering 🟠 Major
while(true) without clear exit 🟠 Major

Prevention Patterns

Always Use Limits

const MAX_ITERATIONS = 1000;

$iterations = 0;
while ($condition && $iterations < self::MAX_ITERATIONS) {
    // ...
    $iterations++;
}

if ($iterations >= self::MAX_ITERATIONS) {
    throw new RuntimeException('Max iterations exceeded');
}

Track Visited Nodes

function traverse($node, array &$visited = []): void
{
    $id = spl_object_id($node);
    if (isset($visited[$id])) {
        return;
    }
    $visited[$id] = true;
    // ...
}

Recursion Depth Limit

function process($data, int $depth = 0): mixed
{
    if ($depth > 100) {
        throw new RuntimeException('Max recursion depth');
    }
    return process($child, $depth + 1);
}

Output Format

### Infinite Loop Risk: [Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**Type:** [Missing Break|Wrong Variable|Unbounded Recursion|...]

**Issue:**
[Description of how infinite loop can occur]

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

Fix:

// With proper termination

Trigger Condition: [When this infinite loop would occur]

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 代码中无限循环风险的全面检测能力,涵盖多种常见场景。
  • 提供了具体的检测模式、grep 模式、严重性分类和预防模式,实用性强。
Trigger Precision95/100

Highlights

  • description 字段提供了清晰的触发描述,涵盖了核心功能。
  • 触发词精准完整,边界清晰。
Structure and Standards95/100

Highlights

  • Skill 结构清晰,分为多个部分,每个部分都有详细的说明和代码示例。
  • frontmatter 完整,单文件未超过 500 行。
Execution Reliability90/100

Highlights

  • 提供了具体的检测模式和 grep 模式,逻辑清晰,覆盖了主要的异常情况。
  • Skill 提供的指导具有高度的可靠性。
Evidence Verifiability (mean of the first four)91/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.