check-idempotency
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 "check-idempotency" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-78ed4a2cf847a88e12f897977c0cbc189df08a64f2664fa923dc8b261ba85a3a. 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
Analyze idempotency issues in PHP code: detect missing idempotency keys on POST/PUT endpoints, non-idempotent command handlers, risks of duplicate writes, and operations unsafe to retry.
Introduction source: third_party · dykyi-roman · 0.0.1 Reference
SkillPi interpretation
- Tasks
- Analyzes PHP code for idempotency issues. Detects missing idempotency keys on POST/PUT endpoints, non-idempotent command handlers, duplicate write risks, and retry-unsafe operations.
- Inputs and outputs
- ```markdown
- Limits and differences
- Grep: "->save\(|->persist\(|->insert\(" --glob "**/*Handler*.php" ```
- Testing
- Not tested
Browse files
Frontmatter
name: check-idempotency
description: Analyzes PHP code for idempotency issues. Detects missing idempotency keys on POST/PUT endpoints, non-idempotent command handlers, duplicate write risks, and retry-unsafe operations.Idempotency Check
Analyze PHP code for idempotency violations that can cause duplicate writes, double charges, or inconsistent state on retries.
Detection Patterns
1. Missing Idempotency Key on POST/PUT Endpoints
<?php
declare(strict_types=1);
// BAD: POST endpoint creates resource without deduplication
final class CreateOrderAction
{
public function __invoke(Request $request): Response
{
$order = $this->orderService->create($request->validated());
return new JsonResponse($order, 201);
// Retry from client = duplicate order!
}
}
// GOOD: POST endpoint requires idempotency key
final class CreateOrderAction
{
public function __invoke(Request $request): Response
{
$idempotencyKey = $request->headers->get('Idempotency-Key');
if ($idempotencyKey === null) {
return new JsonResponse(['error' => 'Idempotency-Key header required'], 422);
}
$existing = $this->idempotencyStore->find($idempotencyKey);
if ($existing !== null) {
return new JsonResponse($existing->payload(), $existing->statusCode());
}
$order = $this->orderService->create($request->validated());
$this->idempotencyStore->save($idempotencyKey, $order, 201);
return new JsonResponse($order, 201);
}
}
2. Non-Idempotent Command Handlers
<?php
declare(strict_types=1);
// BAD: Handler executes without checking previous execution
final readonly class ChargePaymentHandler
{
public function __construct(
private PaymentGateway $gateway,
) {}
public function __invoke(ChargePaymentCommand $command): void
{
// If message is redelivered, payment is charged twice!
$this->gateway->charge($command->amount, $command->cardToken);
}
}
// GOOD: Handler checks for previous execution
final readonly class ChargePaymentHandler
{
public function __construct(
private PaymentGateway $gateway,
private ProcessedCommandStore $processedStore,
) {}
public function __invoke(ChargePaymentCommand $command): void
{
if ($this->processedStore->wasProcessed($command->commandId)) {
return; // Already executed, skip
}
$this->gateway->charge($command->amount, $command->cardToken);
$this->processedStore->markProcessed($command->commandId);
}
}
3. Duplicate Write Risk in Critical Operations
<?php
declare(strict_types=1);
// BAD: Payment without dedup guard
final readonly class PaymentService
{
public function charge(UserId $userId, Money $amount): PaymentResult
{
// No guard against duplicate charges
$result = $this->gateway->charge($userId->toString(), $amount->cents());
$this->repository->save(new Payment($userId, $amount, $result->transactionId()));
return $result;
}
}
// GOOD: Payment with unique constraint and idempotency
final readonly class PaymentService
{
public function charge(UserId $userId, Money $amount, string $requestId): PaymentResult
{
$existing = $this->repository->findByRequestId($requestId);
if ($existing !== null) {
return PaymentResult::fromExisting($existing);
}
$result = $this->gateway->charge(
$userId->toString(),
$amount->cents(),
idempotencyKey: $requestId,
);
$this->repository->save(
new Payment($userId, $amount, $result->transactionId(), $requestId),
);
return $result;
}
}
4. Retry-Unsafe Operations in Retry Loops
<?php
declare(strict_types=1);
// BAD: Email send in retry loop without idempotency guard
final readonly class NotificationService
{
public function sendWithRetry(Notification $notification): void
{
$attempts = 0;
while ($attempts < 3) {
try {
$this->mailer->send($notification->toEmail());
$this->smsService->send($notification->toSms());
return;
} catch (TransportException $e) {
$attempts++;
// Email might have been sent, SMS failed
// Retry sends email AGAIN!
}
}
}
}
// GOOD: Track each step independently with idempotency
final readonly class NotificationService
{
public function sendWithRetry(Notification $notification): void
{
$this->sendStep(
stepId: $notification->id() . ':email',
action: fn () => $this->mailer->send($notification->toEmail()),
);
$this->sendStep(
stepId: $notification->id() . ':sms',
action: fn () => $this->smsService->send($notification->toSms()),
);
}
private function sendStep(string $stepId, callable $action): void
{
if ($this->stepStore->isCompleted($stepId)) {
return;
}
$action();
$this->stepStore->markCompleted($stepId);
}
}
Grep Patterns
# POST/PUT actions without idempotency key check
Grep: "class.*Action|class.*Controller" --glob "**/*Action*.php"
Grep: "Idempotency-Key|idempotency_key|idempotencyKey" --glob "**/*.php"
# Command handlers without dedup check
Grep: "class.*Handler.*\{" --glob "**/*Handler*.php"
Grep: "wasProcessed|isProcessed|alreadyHandled" --glob "**/*Handler*.php"
# Payment/charge operations without idempotency
Grep: "->charge\(|->pay\(|->refund\(|->transfer\(" --glob "**/*.php"
Grep: "findByRequestId|findByIdempotencyKey" --glob "**/*.php"
# Retry loops with side effects
Grep: "while.*retry|for.*attempt|catch.*retry" --glob "**/*.php"
# Email/SMS in retry blocks
Grep: "->send\(.*Email|->send\(.*Sms|mailer->send" --glob "**/*.php"
# Missing unique constraints on write operations
Grep: "->save\(|->persist\(|->insert\(" --glob "**/*Handler*.php"
Severity Classification
| Pattern | Severity |
|---|---|
| Payment/charge without idempotency key | 🔴 Critical |
| Command handler without dedup check | 🔴 Critical |
| POST endpoint without Idempotency-Key | 🟠 Major |
| Email send in retry loop without guard | 🟠 Major |
| Write operation without unique constraint | 🟠 Major |
| Missing idempotency on non-critical updates | 🟡 Minor |
Output Format
### Idempotency Issue: [Brief Description]
**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**Type:** [Missing Key|Non-Idempotent Handler|Duplicate Write|Retry-Unsafe]
**Issue:**
[Description of the idempotency violation]
**Risk:**
- Duplicate charges/payments on retry
- Double email/SMS delivery
- Inconsistent state after network failure
**Code:**
```php
// Problematic pattern
Fix:
// With idempotency guard
## When This Is Acceptable
- **GET/DELETE requests** -- GET is inherently idempotent, DELETE on same resource is safe (returns 404 on retry)
- **Internal synchronous calls** -- Direct method calls within a single transaction boundary don't need idempotency keys
- **Upsert operations** -- INSERT ON CONFLICT UPDATE is inherently idempotent by design
- **Read-only commands** -- Query handlers that only read data don't need dedup checks
### False Positive Indicators
- Operation is wrapped in a database transaction with unique constraint
- Gateway already enforces idempotency (e.g., Stripe idempotency key at SDK level)
- Operation is naturally idempotent (setting a value, not incrementing)Current listing version
0.0.1
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 解决 PHP 开发中幂等性这一关键架构问题,避免资金损失和数据不一致
- 提供具体检测模式和修复示例,实用性强
Highlights
- 触发描述清晰完整,覆盖 POST/PUT 端点、命令处理器、支付操作等核心场景
- 明确列出可接受场景和误报指示器,边界清晰
Areas to improve
-
缺少 When to Use 显式章节 Reported severity: Minor
已有 When This Is Acceptable 内容,但未使用标准章节名且位置靠后
Recommendation: 将 When This Is Acceptable 移至 Detection Patterns 前并改为 When to Use 章节
Highlights
- Detection Patterns 分 4 类,每类含 BAD/GOOD 代码对比,结构清晰
- 提供完整 grep 命令和 Severity Classification,执行指导性强
Highlights
- 基于 grep 模式匹配,无需外部依赖,执行简单可靠
- Severity Classification 明确风险等级,帮助用户优先处理关键问题
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.
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.
User discussion
No verified reviews yet.