# Serialize and roll back an optimistic React cancellation

An optimistic UI can falsely display a completed transition after the server rejected it. Keep a snapshot, allow only one mutation at a time, and use the server-returned state on acknowledgement. A rejected operation restores the local snapshot and exposes its failure.

Save this requirement in Perch and check it after each agent edit. The rule gives your agent a named check to run, a finding to repair, and the same command to recheck.

## Implement the React boundary

Save this illustrative integration module as `src/useCancellation.js`.

```javascript
import { useRef, useState } from "react";

export function useCancellation(initialOrder, cancelOnServer) {
  const [order, setOrder] = useState(initialOrder);
  const [error, setError] = useState(null);
  const inFlight = useRef(false);
  async function cancel() {
    if (inFlight.current) return false;
    inFlight.current = true;
    const previous = order;
    setError(null);
    setOrder({...previous,status:"cancelling"});
    try {
      const confirmed = await cancelOnServer(previous.id, previous.version);
      setOrder(confirmed);
      return true;
    } catch (failure) {
      setOrder(previous);
      setError(failure);
      return false;
    } finally {
      inFlight.current = false;
    }
  }
  return {order,error,cancel};
}
```

The order, inventory, or resource-lifetime scenario is adapted from Perch’s public [order-service source at commit 4af67af](https://github.com/lakeday-org/perch/blob/4af67af46d76ac99398d61c7ad0a45441760d4dc/test/fixtures/order-service/auth.py). This React implementation is an illustrative adaptation.

## Integrate with your application

Mount one hook instance per stable order identity and use it as the only writer of this local order state. cancelOnServer must send the expected version and reject on authorization or concurrency conflicts. A network error may occur after the server committed: the caller must re-fetch authoritative state and block retry until that reconciliation completes; this hook does not implement that reconciliation. Unmounting needs a separate cancellation/ownership policy for long-running work.



## Exercise the boundary and failure paths

| Scenario | Expected outcome |
| --- | --- |
| Server accepts | Authoritative returned order shown |
| Server rejects stale version | Previous local order restored and error shown |
| Double click | Second mutation is not sent |
| Lost acknowledgement | Caller must re-fetch authoritative state and prevent retry until reconciliation |

Add regression tests for these cases in your existing React test project. Use separate connections or deliberately reordered completion where the case involves concurrency; a sequential happy-path test does not exercise that failure. Run the test command after creating the matching test file or suite:

```sh
npx vitest run src/useCancellation.test.jsx
```

The scenarios above specify tests to implement. A completed Perch source check below is separate from running these application integration tests.

## Introduce the specific agent regression

In a throwaway copy, replace this source span:

```javascript
setOrder(previous);
```

with:

```javascript
// Remove the source span shown above.
```

Run the relevant negative test and the Perch command on that broken copy. Restore the corrected source before committing the application. The supplied mutation reproduces the exact regression for the rule check.

## Preserve the requirement as a Perch rule

Save this in `.perch/rules/perch-guide-react-optimistic-mutation-rollback.yaml` at the repository root, keeping your existing `perch.yaml`:

```yaml
- name: optimistic-failure-restores-state
  where: "src/useCancellation.js"
  ensure: >-
    When cancelOnServer rejects, the optimistic cancelling state must be replaced with the previous order before reporting the error.
```

Install and authenticate the CLI once, then check the current working file:

```sh
npm install -g @lakeday/perch
perch login
perch check src/useCancellation.js --rules optimistic-failure-restores-state --json
```

Use Node 22 or newer. The framework can use another language; Perch’s CLI remains a Node command. A gated finding exits 3. Exits 1 or 2 mean the check did not complete and must be reported as a blocker.

## Inspect the captured rule check

On 2026-10-14, Perch using jev-latest checked the exact fixed and broken source provided here. The capture records SHA-256 hashes of both sources and the requirement.

| Source control | Exit | Outcome |
| --- | --- | --- |
| Broken | 3 | Rule finding |
| Corrected | 0 | No rule finding |

The rule distinguished these controls in this run. [Raw Perch capture](/optimistic-mutation-rollback/capture.json) · [Exact sources and mutation](/optimistic-mutation-rollback/source.json).

## Install the rule pack and configure your agent

[Download this rule pack ZIP](/optimistic-mutation-rollback/rule-pack.zip) · [Download the YAML rules](/optimistic-mutation-rollback/rules.yaml) · [Agent task](/optimistic-mutation-rollback/agent-task.txt). The pack contains the rule, its example paths and the repair/recheck instructions. Review the `where` selector before using it in an existing project. Keep your root `perch.yaml`; install this rule as a separate file under `.perch/rules/`.

1. Install Perch using Node 22 or newer and sign in once:

```sh
npm install -g @lakeday/perch
perch login
```

2. Download the pack, inspect it, and extract it from your repository root. The extraction preserves any existing files:

```sh
curl -fL 'https://reporules.fyi/react/optimistic-mutation-rollback/rule-pack.zip' -o 'perch-guide-react-optimistic-mutation-rollback.zip'
unzip -n 'perch-guide-react-optimistic-mutation-rollback.zip'
```

The installed rule is `.perch/rules/perch-guide-react-optimistic-mutation-rollback.yaml`. Its selector matches `src/useCancellation.js` in this example; adapt the selector to your application file before checking an existing project.

3. Configure the coding agent you use. Run one of these commands:

Claude Code:

```sh
perch setup claude-code
```

Codex:

```sh
perch setup codex
```

Cursor:

```sh
perch setup cursor
```

Pi:

```sh
perch setup pi
```

4. Ask the agent to edit the implementation and check the saved requirement:

> Use the installed Perch skill while editing src/useCancellation.js. Preserve optimistic-failure-restores-state. Run perch check src/useCancellation.js --rules optimistic-failure-restores-state --json after the edit. Read each finding and the affected code, fix the implementation, and run the identical check again after the fix. Keep the rule and regression tests intact. Run the application's relevant regression tests and report the commands and actual results. Exit 3 means a rule finding; exit 1 or 2 means the check did not complete. Report an unavailable or incomplete check as blocked. Do not claim the application tests ran if only the Perch check ran.

5. After repairing a finding, run the same check again and inspect the result:

```sh
perch check src/useCancellation.js --rules optimistic-failure-restores-state --json
```

Commit the downloaded rule and the installed agent configuration with your application. The rule file adds no guarantee of correctness; keep the regression tests from this guide.

With the base reference fetched, use `perch scan --since origin/main --filter type=lint` in CI.

## Framework references and verification scope

- [react.dev reference](https://react.dev/reference/react/useRef)
- [react.dev reference](https://react.dev/reference/react/useState)

The dated capture records the source check shown above. Implement the adapters, schema and regression tests described in this guide in your application. Unchanged requests reuse cached answers; fresh model judgments can vary. Model analysis sends relevant source to the configured service.
