> ## Documentation Index
> Fetch the complete documentation index at: https://docs.canary.effectiveai.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Cancel a policy

> Build a procedure that reads a policy, works out the pro rata return premium, gets the refund approved, then cancels, refunds and sends the notice with keys that make a repeat safe.

In this tutorial you build a procedure for an insured's request to cancel a policy. It reads the
policy from your policy system, works out the pro rata return premium, and asks an operations
approver to approve the refund. On approval it writes the cancellation to your policy system,
refunds the premium through your payment processor and sends the cancellation notice on the
cancellation date. If the approver rejects, nothing is written.

## What this does for your team

An insured asks to cancel. The procedure checks that the policy can be cancelled and does the
refund arithmetic. It then puts the request, the dates and the amount in front of an approver.
Nothing changes in your policy system and no money moves until they approve. After approval it
cancels the policy, refunds the premium and sends the notice on the cancellation date, without
anyone having to remember the date. The run keeps a record of what it read, the amount, who
approved it, and the IDs your systems gave the cancellation, refund and notice. If the same request
is run twice, your systems answer with what they already did instead of cancelling, refunding or
mailing again, as long as they honour the keys the procedure sends.

The example carrier is Northwind Mutual. Its hosts, policy numbers, amounts and IDs are made up;
replace them with your own.

## Before you start

You need:

* An API key for a member who is not read-only, and `curl` and `jq`. See
  [Run procedures from your system](https://docs.canary.effectiveai.app/guides/procedures.md), which also covers
  publishing and starting runs. A draft also needs permission to create procedures, or to publish
  this one once it exists. Resource-scoped and app API keys can't start drafts.
* A group in Effective for the people who approve refunds. The procedure assigns its task to
  `group:operations-approvers`; replace that with your group.
* HTTPS APIs for your policy system and payment processor that accept an `Idempotency-Key` header
  on writes and answer a repeated key with their first result. Your policy system must also record
  which request cancelled a policy. The procedure's code calls these endpoints; change the hosts,
  paths and field names to match yours:

| Step | Request | Returns |
| - | - | - |
| Read the policy | `GET https://policy.northwind.example/v1/policies/{policyNumber}` | `status` (such as `in-force` or `cancelled`), `cancellationRequestId` (the `requestId` a cancellation was written with, or `null`), `insuredName`, `termStart`, `termEnd`, `writtenPremiumCents`, `paymentId` |
| Cancel | `POST https://policy.northwind.example/v1/policies/{policyNumber}/cancellations` | `id` |
| Refund | `POST https://api.payments.example/v1/refunds` | `id` |
| Send the notice | `POST https://policy.northwind.example/v1/policies/{policyNumber}/notices` | `id` |

## The procedure

Save this as `cancel-a-policy.procedure.md`. The sections after it walk through each part.

````markdown cancel-a-policy.procedure.md theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
---
kind: procedure@v0
id: cancel-a-policy

inputs:
  request_id: { type: string }
  policy_number: { type: string }
  cancellation_date: { type: string }
  reason: { type: string }
outputs:
  cancellation: { schema: cancellation-result }
run:
  title: 'Cancel {{ $inputs.policy_number }} ({{ $inputs.request_id }})'
---

# Cancel a policy

Cancel a Northwind Mutual policy at the insured's request. The procedure reads
the policy, works out the pro rata return premium, and asks operations to
approve the refund. On approval it cancels the policy, refunds the premium and
sends the cancellation notice on the cancellation date. Each write carries a
key derived from the request, so a system that honours the key applies it once,
even if the procedure runs again for the same request.

## Read the policy

Read the policy from the policy system. A policy in force can be cancelled. A
policy this same request already cancelled goes on too, so that running the
procedure again finishes what an earlier run started. Any other policy ends the
run here, before anyone is asked to approve anything.

```yaml call id=read-policy
function: '@local.get-policy'
input:
  policyNumber: $inputs.policy_number
  requestId: $inputs.request_id
output: policy
```

```yaml choice id=check-policy
on: $policy.standing
cases:
  'in-force': continue
  'cancelled-by-this-request': continue
  'not-cancellable': '#not-cancellable'
```

### Not cancellable {#not-cancellable}

The policy isn't in force, and this request didn't cancel it. Nothing is
written.

```yaml complete id=not-cancellable
output: cancellation
value:
  requestId: $inputs.request_id
  policyNumber: $inputs.policy_number
  status: not-cancellable
  cancellationDate: $inputs.cancellation_date
  policyStatus: $policy.status
```

## Work out the return premium

Pro rata: the insured gets back the share of the written premium for the days
left in the term after the cancellation date.

```yaml call id=compute-return-premium
function: '@local.pro-rata-return'
input:
  termStart: $policy.termStart
  termEnd: $policy.termEnd
  cancellationDate: $inputs.cancellation_date
  writtenPremiumCents: $policy.writtenPremiumCents
output: quote
```

## Approve the refund

An operations approver checks the request and the amount.

```yaml task id=approve-refund
assignees:
  - group:operations-approvers
title: Approve the ${{ $quote.returnPremium }} refund on {{ $inputs.policy_number }}?
instructions: |
  **{{ $policy.insuredName }}** asked to cancel policy {{ $inputs.policy_number }}
  from {{ $inputs.cancellation_date }}. Reason: {{ $inputs.reason }}

  - Policy status: {{ $policy.status }}
  - Term: {{ $policy.termStart }} to {{ $policy.termEnd }} ({{ $quote.termDays }} days)
  - Written premium: ${{ $quote.writtenPremium }}
  - Days left after cancellation: {{ $quote.unearnedDays }}
  - Return premium: ${{ $quote.returnPremium }}

  Approve to cancel the policy and refund ${{ $quote.returnPremium }} to the
  original payment. Reject to stop without writing anything. If the policy
  status is cancelled, an earlier run for this request already cancelled it:
  approve to finish the refund and the notice.
result:
  schema: refund-decision
output: approval
```

A missing note becomes an empty string, so the result always has one.

```yaml value id=read-decision
schema: decision
output: decision
value:
  approved: $approval.value.approved
  note: $approval.value.note ?? ""
```

```yaml choice id=route-decision
on: $decision.approved
cases:
  'true': '#cancel-and-refund'
  'false': '#rejected'
```

### Cancel and refund {#cancel-and-refund}

Write the cancellation to the policy system.

```yaml call id=write-cancellation
function: '@local.create-cancellation'
input:
  requestId: $inputs.request_id
  policyNumber: $inputs.policy_number
  cancellationDate: $inputs.cancellation_date
  returnPremiumCents: $quote.returnPremiumCents
output: cancellation_record
```

Refund the return premium to the payment the insured made.

```yaml call id=issue-refund
function: '@local.create-refund'
input:
  requestId: $inputs.request_id
  paymentId: $policy.paymentId
  amountCents: $quote.returnPremiumCents
output: refund
```

Wait until the notice date, then send the notice.

```yaml wait id=wait-for-notice-date
until: $quote.noticeAt
```

```yaml call id=send-notice
function: '@local.create-notice'
input:
  requestId: $inputs.request_id
  policyNumber: $inputs.policy_number
  cancellationId: $cancellation_record.cancellationId
output: notice
```

```yaml complete id=cancelled
output: cancellation
value:
  requestId: $inputs.request_id
  policyNumber: $inputs.policy_number
  status: cancelled
  cancellationDate: $inputs.cancellation_date
  returnPremiumCents: $quote.returnPremiumCents
  approvalNote: $decision.note
  cancellationId: $cancellation_record.cancellationId
  refundId: $refund.refundId
  noticeId: $notice.noticeId
```

### Rejected {#rejected}

This run wrote nothing. The policy stays as it was: in force, or cancelled by an
earlier run for this request.

```yaml complete id=rejected
output: cancellation
value:
  requestId: $inputs.request_id
  policyNumber: $inputs.policy_number
  status: rejected
  cancellationDate: $inputs.cancellation_date
  returnPremiumCents: $quote.returnPremiumCents
  approvalNote: $decision.note
```

## Resources

### Contracts

```yaml schema id=cancellation-result
type: object
additionalProperties: false
required: [requestId, policyNumber, status, cancellationDate]
properties:
  requestId: { type: string }
  policyNumber: { type: string }
  status: { enum: [cancelled, rejected, not-cancellable] }
  cancellationDate: { type: string }
  policyStatus: { type: string }
  returnPremiumCents: { type: integer }
  approvalNote: { type: string }
  cancellationId: { type: string }
  refundId: { type: string }
  noticeId: { type: string }
```

```yaml schema id=refund-decision
type: object
additionalProperties: false
required: [approved]
properties:
  approved: { type: boolean }
  note: { type: [string, 'null'] }
```

```yaml schema id=decision
type: object
additionalProperties: false
required: [approved, note]
properties:
  approved: { type: boolean }
  note: { type: string }
```

```yaml schema id=policy-request
type: object
additionalProperties: false
required: [policyNumber, requestId]
properties:
  policyNumber: { type: string }
  requestId: { type: string }
```

```yaml schema id=policy
type: object
additionalProperties: false
required:
  [policyNumber, status, standing, insuredName, termStart, termEnd, writtenPremiumCents, paymentId]
properties:
  policyNumber: { type: string }
  status: { type: string }
  standing: { enum: [in-force, cancelled-by-this-request, not-cancellable] }
  insuredName: { type: string }
  termStart: { type: string }
  termEnd: { type: string }
  writtenPremiumCents: { type: integer, minimum: 0 }
  paymentId: { type: string }
```

```yaml schema id=pro-rata-input
type: object
additionalProperties: false
required: [termStart, termEnd, cancellationDate, writtenPremiumCents]
properties:
  termStart: { type: string }
  termEnd: { type: string }
  cancellationDate: { type: string }
  writtenPremiumCents: { type: integer, minimum: 0 }
```

```yaml schema id=return-quote
type: object
additionalProperties: false
required: [termDays, unearnedDays, writtenPremium, returnPremiumCents, returnPremium, noticeAt]
properties:
  termDays: { type: integer }
  unearnedDays: { type: integer }
  writtenPremium: { type: string, format: decimal }
  returnPremiumCents: { type: integer }
  returnPremium: { type: string, format: decimal }
  noticeAt: { type: string, format: date-time }
```

```yaml schema id=cancel-request
type: object
additionalProperties: false
required: [requestId, policyNumber, cancellationDate, returnPremiumCents]
properties:
  requestId: { type: string }
  policyNumber: { type: string }
  cancellationDate: { type: string }
  returnPremiumCents: { type: integer }
```

```yaml schema id=cancellation-record
type: object
additionalProperties: false
required: [cancellationId]
properties:
  cancellationId: { type: string }
```

```yaml schema id=refund-request
type: object
additionalProperties: false
required: [requestId, paymentId, amountCents]
properties:
  requestId: { type: string }
  paymentId: { type: string }
  amountCents: { type: integer }
```

```yaml schema id=refund-record
type: object
additionalProperties: false
required: [refundId]
properties:
  refundId: { type: string }
```

```yaml schema id=notice-request
type: object
additionalProperties: false
required: [requestId, policyNumber, cancellationId]
properties:
  requestId: { type: string }
  policyNumber: { type: string }
  cancellationId: { type: string }
```

```yaml schema id=notice-record
type: object
additionalProperties: false
required: [noticeId]
properties:
  noticeId: { type: string }
```

### Secrets

```yaml secret id=policy-system-token
format: text
description: API token for the Northwind Mutual policy system
```

```yaml secret id=payments-token
format: text
description: API key for the payment processor
```

### Code

Pro rata return premium, in whole cents. The day count uses calendar
arithmetic because pure functions have no clock or `Date`.

```ts function id=pro-rata-return input=pro-rata-input result=return-quote
(input) => {
  const dayNumber = (date: string): number => {
    const parts = date.split('-');
    let year = Number.parseInt(parts[0] ?? '', 10);
    const month = Number.parseInt(parts[1] ?? '', 10);
    const day = Number.parseInt(parts[2] ?? '', 10);
    if (Number.isNaN(year) || Number.isNaN(month) || Number.isNaN(day)) {
      throw new Error(`${date} is not a YYYY-MM-DD date.`);
    }
    year -= month <= 2 ? 1 : 0;
    const era = Math.floor(year / 400);
    const yearOfEra = year - era * 400;
    const dayOfYear = Math.floor((153 * ((month + 9) % 12) + 2) / 5) + day - 1;
    const dayOfEra =
      yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
    return era * 146097 + dayOfEra;
  };
  const dollars = (cents: number): string =>
    `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, '0')}`;

  const start = dayNumber(input.termStart);
  const end = dayNumber(input.termEnd);
  const cancel = dayNumber(input.cancellationDate);
  if (cancel < start || cancel > end) {
    throw new Error('The cancellation date is outside the policy term.');
  }
  const termDays = end - start;
  const unearnedDays = end - cancel;
  const returnPremiumCents = Math.round((input.writtenPremiumCents * unearnedDays) / termDays);
  return {
    termDays,
    unearnedDays,
    writtenPremium: dollars(input.writtenPremiumCents),
    returnPremiumCents,
    returnPremium: dollars(returnPremiumCents),
    noticeAt: `${input.cancellationDate}T14:00:00Z`,
  };
};
```

Read the policy and work out its standing for this request. A 4xx answer other
than 429 can't change on another attempt, so it stops the run with
`FatalError`; anything else is retried.

```ts effect id=get-policy input=policy-request result=policy uses=fetch,secrets secrets=policy-system-token
async ({ policyNumber, requestId }, { fetch, secrets, signal, FatalError }) => {
  const token = await secrets.getText('policy-system-token');
  const response = await fetch(`https://policy.northwind.example/v1/policies/${policyNumber}`, {
    headers: { Authorization: `Bearer ${token}` },
    signal,
  });
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`Policy ${policyNumber} could not be read (${response.status}).`);
  }
  if (!response.ok) throw new Error(`Policy system answered ${response.status}.`);
  const body = await response.json();
  if (
    typeof body !== 'object' ||
    body === null ||
    !('status' in body) ||
    typeof body.status !== 'string' ||
    !('insuredName' in body) ||
    typeof body.insuredName !== 'string' ||
    !('termStart' in body) ||
    typeof body.termStart !== 'string' ||
    !('termEnd' in body) ||
    typeof body.termEnd !== 'string' ||
    !('writtenPremiumCents' in body) ||
    typeof body.writtenPremiumCents !== 'number' ||
    !('paymentId' in body) ||
    typeof body.paymentId !== 'string'
  ) {
    throw new FatalError('The policy system returned a policy in an unexpected shape.');
  }
  const cancelledBy =
    'cancellationRequestId' in body && typeof body.cancellationRequestId === 'string'
      ? body.cancellationRequestId
      : null;
  let standing: 'in-force' | 'cancelled-by-this-request' | 'not-cancellable' = 'not-cancellable';
  if (body.status === 'in-force') {
    standing = 'in-force';
  } else if (body.status === 'cancelled' && cancelledBy === requestId) {
    standing = 'cancelled-by-this-request';
  }
  return {
    policyNumber,
    status: body.status,
    standing,
    insuredName: body.insuredName,
    termStart: body.termStart,
    termEnd: body.termEnd,
    writtenPremiumCents: body.writtenPremiumCents,
    paymentId: body.paymentId,
  };
};
```

Each write sends a key built from the request ID. If a reply is lost and the
effect runs again, the receiving system sees the same key and returns its
first answer instead of writing twice.

```ts effect id=create-cancellation input=cancel-request result=cancellation-record uses=fetch,secrets secrets=policy-system-token
async (
  { requestId, policyNumber, cancellationDate, returnPremiumCents },
  { fetch, secrets, signal, FatalError }
) => {
  const token = await secrets.getText('policy-system-token');
  const response = await fetch(
    `https://policy.northwind.example/v1/policies/${policyNumber}/cancellations`,
    {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Idempotency-Key': `cancel-${requestId}`,
      },
      body: JSON.stringify({ requestId, effectiveDate: cancellationDate, returnPremiumCents }),
      signal,
    }
  );
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`The policy system refused the cancellation (${response.status}).`);
  }
  if (!response.ok) throw new Error(`Policy system answered ${response.status}.`);
  const body = await response.json();
  if (typeof body !== 'object' || body === null || !('id' in body) || typeof body.id !== 'string') {
    throw new FatalError('The policy system did not return a cancellation ID.');
  }
  return { cancellationId: body.id };
};
```

```ts effect id=create-refund input=refund-request result=refund-record uses=fetch,secrets secrets=payments-token
async ({ requestId, paymentId, amountCents }, { fetch, secrets, signal, FatalError }) => {
  const key = await secrets.getText('payments-token');
  const response = await fetch('https://api.payments.example/v1/refunds', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${key}`,
      'Content-Type': 'application/json',
      'Idempotency-Key': `refund-${requestId}`,
    },
    body: JSON.stringify({ payment: paymentId, amount: amountCents, currency: 'usd' }),
    signal,
  });
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`The payment processor refused the refund (${response.status}).`);
  }
  if (!response.ok) throw new Error(`Payment processor answered ${response.status}.`);
  const body = await response.json();
  if (typeof body !== 'object' || body === null || !('id' in body) || typeof body.id !== 'string') {
    throw new FatalError('The payment processor did not return a refund ID.');
  }
  return { refundId: body.id };
};
```

```ts effect id=create-notice input=notice-request result=notice-record uses=fetch,secrets secrets=policy-system-token
async ({ requestId, policyNumber, cancellationId }, { fetch, secrets, signal, FatalError }) => {
  const token = await secrets.getText('policy-system-token');
  const response = await fetch(
    `https://policy.northwind.example/v1/policies/${policyNumber}/notices`,
    {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Idempotency-Key': `notice-${requestId}`,
      },
      body: JSON.stringify({ type: 'cancellation', cancellationId }),
      signal,
    }
  );
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`The policy system refused the notice (${response.status}).`);
  }
  if (!response.ok) throw new Error(`Policy system answered ${response.status}.`);
  const body = await response.json();
  if (typeof body !== 'object' || body === null || !('id' in body) || typeof body.id !== 'string') {
    throw new FatalError('The policy system did not return a notice ID.');
  }
  return { noticeId: body.id };
};
```
````

## How it works

### Inputs and output

The front matter declares four inputs. `request_id` is your own ID for this cancellation request,
such as the case number your intake system gave it. The procedure builds its write keys from it,
so use a value that is unique to the request and stays the same if the request is sent again.
`cancellation_date` is a `YYYY-MM-DD` date.

The output, `cancellation`, follows the `cancellation-result` schema. All three endings return it:
`status` is `cancelled`, `rejected` or `not-cancellable`. The IDs of what was written appear only
on the `cancelled` path, and `policyStatus` only on the `not-cancellable` path. `run.title` names
each run after its policy and request, so runs are easy to find.

### Read the policy

The `read-policy` node is a [`call`](https://docs.canary.effectiveai.app/procedures/reference/nodes/call) to the local effect
`get-policy`, declared under **Code**. A `ts effect` is TypeScript you write and publish with the
procedure. This one may make HTTPS requests with `fetch` and read one secret,
`policy-system-token`, because its header says `uses=fetch,secrets secrets=policy-system-token`.
The secret's value is never in the source; you set it in Effective after you publish. See
[Functions and effects](https://docs.canary.effectiveai.app/procedures/reference/nodes/function-and-effect.md) and
[`secret`](https://docs.canary.effectiveai.app/procedures/reference/nodes/secret).

The effect checks the shape of the response before it returns it, because the result must match
the `policy` schema. A 4xx answer other than `429` throws `FatalError`: another attempt can't change
it, so the run fails at once. A `429`, a 5xx answer or a network error throws an ordinary error,
which is retried.

The effect also returns the policy's `standing` for this request, worked out from `status` and
`cancellationRequestId`:

| `standing` | When |
| - | - |
| `in-force` | `status` is `in-force` |
| `cancelled-by-this-request` | `status` is `cancelled` and `cancellationRequestId` is `request_id` |
| `not-cancellable` | Anything else, such as a lapsed policy or one another request cancelled |

`check-policy` is a [`choice`](https://docs.canary.effectiveai.app/procedures/reference/nodes/choice) on `standing`. The first two
cases `continue` to the rest of the procedure. `not-cancellable` runs **Not cancellable**, which
completes the run with `status: not-cancellable` and the policy's `status`, before anyone is asked
to approve anything. Returning the standing as data, instead of failing the run, gives your system
a typed answer it can act on, and lets a second run for the same request get past this step. See
[If a run fails partway](#if-a-run-fails-partway).

### Work out the return premium

`compute-return-premium` calls `pro-rata-return`, a `ts function`. A function is pure: it gets only
its input, with no network, secrets or clock. The same input always gives the same result, so the
step is safe to compute again. A pure function can't use `Date`, so it counts days with calendar
arithmetic.

Pro rata means the insured gets back the share of the written premium for the days left in the
term after the cancellation date:

```text theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
return premium = written premium × days left after cancellation ÷ days in term
```

For the illustrative policy, the term runs from 2026-03-01 to 2027-03-01 and the written premium is
\$1,840.00. Cancelled from 2026-12-15:

```text theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
days in term     = 2027-03-01 − 2026-03-01 = 365
days left        = 2027-03-01 − 2026-12-15 = 17 + 31 + 28 = 76
return premium   = 184,000 cents × 76 ÷ 365 = 38,312.33 cents, rounded to 38,312
                 = $383.12
earned premium   = $1,840.00 − $383.12 = $1,456.88
```

The function works in whole cents and rounds once, at the end. It returns the amounts as cents for
the writes, and as decimal text such as `383.12` for the approver to read. It also returns
`noticeAt`, the time to send the notice: 14:00 UTC on the cancellation date. If your carrier uses
short-rate tables or a minimum earned premium, change this function; the rest of the procedure
doesn't change.

A cancellation date before the term starts or after it ends makes the function throw. A
function's error is final, so the run fails at `compute-return-premium`, before anyone is asked to
approve, and its `failure` doesn't say which date was wrong. Check the date in your own system
before you start the run.

### Approve the refund

`approve-refund` is a [`task`](https://docs.canary.effectiveai.app/procedures/reference/nodes/task). It creates a task for the
`operations-approvers` group and the run waits, without holding anything, until someone in that
group answers. The `title` and `instructions` fill in the policy's facts and the arithmetic with
`{{ ... }}`, so the approver sees what they're approving. The answer must match the
`refund-decision` schema: `approved`, and an optional `note`.

`read-decision` is a [`value`](https://docs.canary.effectiveai.app/procedures/reference/nodes/value) node. It copies the answer and
turns a missing note into an empty string with `??`, so later steps can rely on `decision.note`.

### Approved or rejected

`route-decision` is a [`choice`](https://docs.canary.effectiveai.app/procedures/reference/nodes/choice) on `decision.approved`. A
choice has one case for each value: here `'true'` and `'false'`. Each case names a heading
directly under the choice's section, and that heading's nodes run for that case.

* **Rejected.** The `rejected` node completes the run with `status: rejected`. The run writes
  nothing to your systems. On a first run the policy stays in force; for a run that follows a
  failed one, see [If a run fails partway](#if-a-run-fails-partway).
* **Approved.** The run continues under **Cancel and refund**.

Both cases end in a [`complete`](https://docs.canary.effectiveai.app/procedures/reference/nodes/complete) node, so the choice needs
nothing after it.

### Cancel, refund and notify, each with a key

The approved path makes three writes, each in its own `call`: `write-cancellation`,
`issue-refund` and `send-notice`. Separate nodes give each write its own recorded result. If the
refund fails after the cancellation succeeded, the run's record shows exactly which write
happened.

Each effect sends a key built from the request ID:

```ts theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
'Idempotency-Key': `refund-${requestId}`,
```

Your system's handling of that key is what keeps a repeated write from applying twice. Here is
what happens when a reply is lost:

1. `create-refund` sends the refund with `Idempotency-Key: refund-CR-20931`. The processor makes
   the refund, but the connection drops before the reply arrives.
2. `fetch` throws, so the attempt fails. Effects get three attempts by default, with a short
   backoff between them.
3. The second attempt sends the same request with the same key. The processor recognizes the
   key and returns the refund it already made. There is one refund.
4. The run records that result and moves on. If the run is interrupted later and resumes,
   `issue-refund` doesn't run again: the run uses the result it recorded.

Retries alone don't prevent a duplicate: they bound how many times the effect runs. A retry
repeats the request; only the receiving system's key handling stops the repeat from refunding
twice. If one of your endpoints doesn't accept an idempotency key, a
[retry policy](https://docs.canary.effectiveai.app/procedures/reference/nodes/retry.md) with `maximum_attempts: 1` stops the effect from
retrying within one call, and a failure there becomes something a person checks. It doesn't help
across runs: a second run for the same request makes its own first attempt. For that, the
receiving system has to deduplicate, or the procedure has to look for the earlier write by a
business key, such as the request ID, before it writes. See
[Writes to your systems](https://docs.canary.effectiveai.app/procedures/concepts/writes-to-your-systems.md).

The keys come from the request, not from the run. The context's `operation.idempotencyKey` is
also stable across every attempt of one call, but it differs between runs. A key derived from the
request is the same in every run for that request, so if a second run for the same request gets
past `check-policy`, your systems answer it with the cancellation, refund and notice they already
made, for as long as they keep the key.

### Send the notice on the cancellation date

`wait-for-notice-date` is a [`wait`](https://docs.canary.effectiveai.app/procedures/reference/nodes/wait) with `until`. The run
sleeps until `quote.noticeAt` and then continues; it holds nothing while it waits. A date in the
past ends the wait at once, so a backdated cancellation sends its notice straight away. Then
`send-notice` sends the notice with its own key, `notice-CR-20931`.

To send the notice as soon as the refund is issued instead, delete the `wait` node.

### Finish

The `cancelled` node completes the run. Its value must match `cancellation-result`, which
the procedure checks when you publish it and again when the run completes.

### If a run fails partway

A run can fail after some writes and before others: for example, the payment processor refuses the
refund after the cancellation was written. The run ends `failed`, and the cancellation stays
written; failing the run doesn't undo it. There is no step that catches the failure. A failed
run's status is final, and the API has no way to resume it.

The run's `failure` names the step that failed, `issue-refund`, and its code, but not the message
the effect threw: Effective doesn't show thrown messages, because they could hold secret values.
Look in the processor's own logs for why it refused. A refusal the procedure has to act on belongs
in a typed result instead, as `get-policy` returns `standing`.

To recover, fix what made the refund fail and start a new run with the same inputs, including the
same `request_id`. The new run:

1. Reads the policy. It is now `cancelled`, with `cancellationRequestId` set to this request, so
   its standing is `cancelled-by-this-request` and the run goes on.
2. Works out the same return premium from the same term and premium, and asks for approval
   again. The task shows the policy status, so the approver can see it is already cancelled. The
   amount was approved in the failed run, so approve it again to finish. A rejection ends the run
   `rejected` and writes nothing more, but the cancellation the failed run wrote stays. The policy
   is then cancelled with no refund, until you reverse the cancellation in your policy system or
   approve another run for the request.
3. Sends the cancellation with `cancel-CR-20931` again. Your policy system honours the key, so it
   answers with the cancellation it already made, and nothing is written twice.
4. Sends the refund and the notice, which the failed run never made.

Start the new run with its own run `Idempotency-Key`, such as `cancel-CR-20931-2`. The run key only
deduplicates the start request: the same key as the failed run's start returns that failed run
instead of starting a new one.

In the Effective app, **Retry** on the failed run's page also starts a new run, from a checkpoint
of the failed run that you pick. The page shows what starts again from there, and each call from
that point on runs again. The keys above make your systems answer a write they already applied
with its first result.

## Try it as a draft

A draft runs source without publishing it. See
[Try a draft](https://docs.canary.effectiveai.app/guides/procedures.md#try-a-draft). A draft can't declare secrets, and
this procedure declares two, so sending `cancel-a-policy.procedure.md` as a draft is refused with
`422 invalid_procedure` and no run starts.

To try the flow before you connect your systems, make a stand-in copy that runs without secrets.
Save it as `cancel-a-policy.draft.procedure.md` and change three things:

1. Delete the two `yaml secret` blocks under **Secrets**.

2. Replace each `ts effect` with one that returns sample data and declares no `uses=` or
   `secrets=`. For example:

   ```ts effect id=get-policy input=policy-request result=policy theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
   async ({ policyNumber }, _context) => ({
     policyNumber,
     status: 'in-force',
     standing: 'in-force',
     insuredName: 'Dana Whitfield',
     termStart: '2026-03-01',
     termEnd: '2027-03-01',
     writtenPremiumCents: 184000,
     paymentId: 'pay_8KX2',
   });
   ```

   ```ts effect id=create-refund input=refund-request result=refund-record theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
   async (_input, _context) => ({ refundId: 'rf_test_1' });
   ```

   Do the same for `create-cancellation` and `create-notice`, returning a `cancellationId` and a
   `noticeId`.

3. Assign the task to yourself, so you can answer it:

   ```yaml theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
   assignees:
     - 'user:{{ $run.principal.id }}'
   ```

Keep the function and everything else as it is. Then start the draft:

```bash theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
curl --request POST \
  --url "https://api.canary.effectiveai.app/api/v2/procedures/runs" \
  --header "Authorization: Bearer $EFFECTIVE_API_KEY" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: cancel-a-policy-draft-1" \
  --data "$(jq --null-input --rawfile source cancel-a-policy.draft.procedure.md '{
    sourceName: "cancel-a-policy.draft.procedure.md",
    source: $source,
    inputs: {
      request_id: "CR-20931",
      policy_number: "NW-100234",
      cancellation_date: "2026-12-15",
      reason: "Home sold"
    }
  }')"
```

An illustrative response, abbreviated; your IDs differ:

```json theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
{
  "outcome": "started",
  "run": {
    "id": "7c41e9d2-58b3-4f0a-9e6d-2a1b3c4d5e6f",
    "procedureId": "cancel-a-policy",
    "version": null,
    "draft": true,
    "status": "starting",
    "visibility": "private"
  }
}
```

The run stops at the approval task. Find it with
`GET /procedures/tasks?status=open&assignedToMe=true`, read it to check the title and instructions,
and answer it as in [Answer a task](https://docs.canary.effectiveai.app/guides/procedures.md#answer-a-task):

```bash theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
curl --request POST \
  --url "https://api.canary.effectiveai.app/api/v2/procedures/tasks/3e8f1a2b-4c5d-4e6f-8a9b-0c1d2e3f4a5b/submissions" \
  --header "Authorization: Bearer $EFFECTIVE_API_KEY" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: approve-CR-20931-draft-1" \
  --data '{ "answer": { "approved": true, "note": "Sale confirmed" } }'
```

Use the task ID from your own task list. If the cancellation date is still in the future, the run
then waits until 14:00 UTC that day before it sends the notice, and stays `running` until then. Use
a past date to see it finish straight away; the return premium changes with the date.

Each edit to the draft needs a new `Idempotency-Key`.

## Check the result

Read the run with `GET /procedures/runs/{runId}` until `status` is `completed`. For the inputs
above and an approval, `output` looks like this (illustrative):

```json theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
{
  "status": "completed",
  "output": {
    "cancellation": {
      "requestId": "CR-20931",
      "policyNumber": "NW-100234",
      "status": "cancelled",
      "cancellationDate": "2026-12-15",
      "returnPremiumCents": 38312,
      "approvalNote": "Sale confirmed",
      "cancellationId": "cxl_test_1",
      "refundId": "rf_test_1",
      "noticeId": "ntc_test_1"
    }
  },
  "failure": null
}
```

Check that:

* `returnPremiumCents` is `38312`, the \$383.12 worked out above. Open the run's `webUrl` to see
  `compute-return-premium`'s full result, with `termDays: 365` and `unearnedDays: 76`.
* `tasks` lists the approval task as `completed`.
* A rejected draft (answer `{ "approved": false }`) completes with `status: "rejected"`, an empty
  `approvalNote`, and no `cancellationId`, `refundId` or `noticeId`.
* With `status: 'lapsed'` and `standing: 'not-cancellable'` in the stand-in `get-policy`, the run
  completes with `status: "not-cancellable"` and `policyStatus: "lapsed"`, and creates no task.

## Run it against your systems

When the flow does what you want, publish the real `cancel-a-policy.procedure.md`, as in
[Publish a version](https://docs.canary.effectiveai.app/guides/procedures.md#publish-a-version). Reading the version lists
the two secrets it needs under `secrets`. Before the first run, set their values on the
procedure's page in the Effective app, under **Secrets**: a shared default for every run, or a
personal override for the runs that run as you. See
[Give a secret a value](https://docs.canary.effectiveai.app/procedures/reference/nodes/secret.md#give-a-secret-a-value).

Try it on a test policy first. If your policy system and payment processor have test environments,
publish a copy with its own `id`, such as `cancel-a-policy-test`, whose effects call your test
hosts, and give that copy test credentials. Secrets are set for each procedure, so the copy's
values don't affect the real procedure's.

Then check what only your systems can show:

* One cancellation, one refund and one notice for the request, with the IDs the run returned.
* Start a second run with the same `request_id` and approve it. Its `read-policy` step should
  report the standing `cancelled-by-this-request`, and your systems should answer with the same
  cancellation, refund and notice IDs; nothing should be written twice. If the run ends
  `not-cancellable`, your policy system isn't returning `cancellationRequestId`. If an ID differs,
  that endpoint isn't honoring the key. A one-attempt retry policy doesn't help across runs, so
  before you go live, make the endpoint deduplicate on the key, or have its effect look up the
  earlier write by `request_id` before it writes.
* Start a run with a different `request_id` for the same policy. It should end `not-cancellable`
  without creating a task.

Start live runs from your own system with a run `Idempotency-Key` derived from the request, such
as `cancel-CR-20931`, as in [Start a run](https://docs.canary.effectiveai.app/guides/procedures.md#start-a-run).

## Next steps

* [Reconcile payments](https://docs.canary.effectiveai.app/procedures/tutorials/reconcile-payments.md): loop over a day's payments and
  hand only the mismatches the procedure can't explain to a person.
* [Writes to your systems](https://docs.canary.effectiveai.app/procedures/concepts/writes-to-your-systems.md): retries, idempotency keys
  and what to do when an endpoint has no key.
* [`task`](https://docs.canary.effectiveai.app/procedures/reference/nodes/task) and [`choice`](https://docs.canary.effectiveai.app/procedures/reference/nodes/choice):
  every field of the nodes this tutorial uses for the approval.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.