Framework RecipesImplementation, failure path, check

Reject stale Rails cancellation decisions with optimistic locking

Active Record detects a write conflict after the record is loaded, but it cannot infer that a customer made a decision using an older screen. Compare the submitted version first, then let lock_version protect the save from a race that occurs during this request.

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 Rails boundary

Save this illustrative integration module as app/services/cancel_order.rb.

class CancelOrder
  def self.call(actor, order_id, expected_version)
    order = actor.orders.find(order_id)
    raise "stale order" unless order.lock_version == expected_version
    raise "not pending" unless order.status == "pending"
    order.status = "cancelled"
    order.save!
    order
  rescue ActiveRecord::StaleObjectError
    raise "stale order"
  end
end

The order, inventory, or resource-lifetime scenario is adapted from Perch’s public order-service source at commit 4af67af. This Rails implementation is an illustrative adaptation.

Integrate with your application

Add an integer lock_version column with default 0 and use the authenticated actor.orders scope. Validate expected_version as an integer in the controller. Return a conflict response for a stale version and show the latest order; do not automatically retry a customer’s stale cancellation decision.

Exercise the boundary and failure paths

Scenario Expected outcome
Screen version matches pending row Cancel succeeds
Screen version is older Conflict with no mutation
Another request updates after load StaleObjectError mapped to conflict
Another user submits id Scoped lookup rejects

Add regression tests for these cases in your existing Rails 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:

bin/rails test test/services/cancel_order_test.rb

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:

raise "stale order" unless order.lock_version == expected_version

with:

// 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-rails-optimistic-cancellation.yaml at the repository root, keeping your existing perch.yaml:

- name: submitted-order-version
  where: "app/services/cancel_order.rb"
  ensure: >-
    The cancellation must reject when the supplied expected_version differs from order.lock_version before changing status.

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

npm install -g @lakeday/perch
perch login
perch check app/services/cancel_order.rb --rules submitted-order-version --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 · Exact sources and mutation.

Install the rule pack and configure your agent

Download this rule pack ZIP · Download the YAML rules · Agent task. 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:
npm install -g @lakeday/perch
perch login
  1. Download the pack, inspect it, and extract it from your repository root. The extraction preserves any existing files:
curl -fL 'https://frameworkrecipes.dev/rails/optimistic-cancellation/rule-pack.zip' -o 'perch-guide-rails-optimistic-cancellation.zip'
unzip -n 'perch-guide-rails-optimistic-cancellation.zip'

The installed rule is .perch/rules/perch-guide-rails-optimistic-cancellation.yaml. Its selector matches app/services/cancel_order.rb in this example; adapt the selector to your application file before checking an existing project.

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

Claude Code:

perch setup claude-code

Codex:

perch setup codex

Cursor:

perch setup cursor

Pi:

perch setup pi
  1. Ask the agent to edit the implementation and check the saved requirement:

Use the installed Perch skill while editing app/services/cancel_order.rb. Preserve submitted-order-version. Run perch check app/services/cancel_order.rb --rules submitted-order-version --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.

  1. After repairing a finding, run the same check again and inspect the result:
perch check app/services/cancel_order.rb --rules submitted-order-version --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

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.