# Conflicts

Two people, or one person in two tabs or offline, can edit the same record. By default the server accepts or
refuses each call on its own, and the last write wins. An action can instead declare the version of the data
it was based on; `handle_action/4` compares it with the current version and answers a stale call with a
conflict. The server stays the authority: the client rolls the call back, shows the server's state and reports
the conflict, and a resolver on the action may send the call again on top of the newer version.

```js
const tasks = createStore("tasks", {
  state: { tasks: [] }, // each task: { id, title, done, version }
  actions: {
    renameTask: {
      apply: (state, id, title) => ({
        tasks: state.tasks.map((task) => (task.id === id ? { ...task, title } : task)),
      }),
      server: "rename_task",
      // The version this call is based on, read from the confirmed state. Sent as meta.base.
      base: (state, id) => state.tasks.find((task) => task.id === id)?.version ?? null,
      // The record this call changes, from its arguments, named across every action of the store (see below).
      record: (id) => ["task", id],
    },
    toggleTask: {
      apply: (state, id, done) => ({
        tasks: state.tasks.map((task) => (task.id === id ? { ...task, done } : task)),
      }),
      server: "toggle_task",
      base: (state, id) => state.tasks.find((task) => task.id === id)?.version ?? null,
      record: (id) => ["task", id],
      // "Done" means the same on a newer version: send the call again on it, unless the task is gone.
      onConflict: ({ args, state }) => (state.tasks.some((task) => task.id === args[0]) ? { args } : null),
    },
  },
  maxResubmits: 3, // the default: how many times resolvers may send one call again
});

// Every conflict, also the ones a resolver sent again (they carry resubmittedAs).
tasks.onConflict((conflict) => showNotice(conflict));

tasks.actions.renameTask("t1", "Buy green tea").catch((error) => {
  if (error.conflict) console.log("the server holds", error.state, "because", error.reason);
});
```

```elixir
@impl LiveSlice
def handle_action(:rename_task, [task_id, title], %{id: mutation_id} = meta, socket) do
  cond do
    # 1. A call whose reply was lost comes back with the same id and the same base. Its own first run moved
    #    the version, so look the id up first and answer it as the first time.
    applied?(mutation_id) ->
      {:ok, %{tasks: list_tasks()}, socket}

    # 2. Then compare the version. The client merges the state over its own (the server wins).
    meta[:base] != version_of(task_id) ->
      {:conflict, %{tasks: list_tasks()}, socket}

    # 3. Reply with the new version, so the client's next edit of the task is based on it.
    true ->
      rename!(task_id, title, mutation_id)
      {:ok, %{tasks: list_tasks()}, socket}
  end
end
```

`LiveSlice`'s module documentation has the same handler with Ecto and an integer `lock_version`
(`Ecto.Changeset.optimistic_lock/3`); an `updated_at` stamp works the same way. The demo's `Demo.Tasks` keeps
the processed ids and the version check in one Agent call.

- **`base(confirmedState, ...args)`** is evaluated when the action is called, on the confirmed state (what the
  server last confirmed, not the optimistic state with pending calls applied), and kept as a JSON copy on the
  pending call (`undefined` becomes `null`). `pending()` lists it, it is persisted and shared between tabs with
  the queue, and the bridge sends it in the `live_slice:action` payload. A `base` that throws on the call
  throws to the caller and records nothing. `handle_action/4` receives it as `meta.base`, present when the
  client sent one (`meta[:base]` is `nil` otherwise; a call queued before its action declared `base` is sent
  with `null`).
- **The reply.** `{:conflict, state, socket}` or `{:conflict, state, reason, socket}` is sent as
  `{ok: false, conflict: true, reason, state}`, with `"conflict"` as the reason unless one is given, through
  the same JSON guard as the other replies (a struct or unencodable state is left out and logged, an
  unencodable reason becomes `"invalid_reason"`).
- **On the client** the call is rolled back and `state` is merged into the confirmed state, so the server
  wins; later queued calls stay applied on top. `onConflict` listeners get
  `{id, action, server, args, at, base, reason, conflict: true, state, resubmittedAs?}`. Without a resolver (or
  when it gives up), the promise of the call rejects with `{conflict: true, reason, state}`, and `onRejected`
  and `onSettled` report it like a rejection with `conflict: true` and `state` added.
- **The resolver** `onConflict(context)` is called after the server's state was merged, with
  `{id, action, args, at, base, reason, serverState, state}` (`state` is the new confirmed state). It returns
  `{ args }` to send the call again, or `null`/`undefined` to give up; one that throws gives up and is
  reported with `console.error`. A resubmitted call is a new call with a new id (the server remembers the
  old id's outcome) and a base evaluated on the new confirmed state; it takes the old call's place in the
  queue, so calls made after it still reach the server after it, and the promise of the original call follows
  it. The old call is reported to `onSettled` with status `"resubmitted"` and `resubmittedAs`, not to
  `onRejected`, and the new one to `onPending`. A call is sent again at most `maxResubmits` times (a store
  option, 3 by default), so two clients that keep conflicting cannot loop forever.
- **`record(...args)`** names the one record a call changes: any JSON value, such as `[type, id]`; `null` or
  `undefined` names none for that call. It is evaluated when the action is called, from the arguments only,
  also on an action without `base`, and kept as a JSON copy on the pending call: `pending()` lists it, and it is
  persisted and shared between tabs with the queue, so a reload or another tab taking the queue over uses the
  record computed then and never evaluates it again. It is not sent to the server. Two calls concern the same
  record only when both declared one and the two are equal by content. Equal versions are no evidence: two
  tasks can both be at version 1. Records are compared across every action of the store, not per action, so a
  record must identify its record among all of them: with `(id) => id` on both `renameTask` and `renameList`,
  task 1 and list 1 would count as one record, and a confirmed rename of task 1 could move the base of a queued
  rename of list 1 over another user's change of that list. Name the kind as well as the id (`["task", id]`).
  It must also name the record whose version `base` reads, since the base of one call moves on what another
  call of the same record confirms. A `record` that throws on the call throws to the caller and records
  nothing. Declare it only for an action that changes that one record; an action that changes several records
  (a reorder, a move between lists) leaves it out.
- **Your own queued edits do not conflict with each other.** A call queued behind another call of the same
  queue was based on the version before that one. When the earlier call is confirmed, every later call whose
  base still equals what `base` gives on the confirmed state before that confirmation gets its base evaluated
  again on the confirmed state after it (the reply's state included). So two quick edits of one record, or
  several edits queued offline and replayed after a reconnect, each go out on the version the previous one
  produced. A version that changed in the confirmed state before (a patch, an invalidate, `setState`, another
  tab's settled call) is not the queue's own doing: those calls keep their base and conflict, which is the
  point. A change from elsewhere that this client did not get before the confirmation, but only inside the
  reply, is taken as seen: patch each change to every client as it happens to keep that window short (see
  [Known limits](known-limits.md)). When both calls declared a record and the records differ, the later base does
  not move at all: a change of its record that arrives inside the confirmation of another record came from
  elsewhere, so the call conflicts. For this to work, return the record's new version in the reply state (as
  above) or let `apply` set the version the server will set. Calls restored after a reload or called before
  hydration finished follow the same rule.
- **The confirmed call's own effect may arrive first.** A reply that was lost and the reconnect's mount patch
  that already holds the call, a patch the handler sends to its own LiveView from inside `handle_action/4` (it
  arrives before the reply), or this tab's patch arriving before another tab's settlement announcement all put
  the earlier call's new version in the confirmed state before its confirmation, so a later call no longer
  matches it. When both calls declared the same record, and the later call's base equals the base the
  confirmed call was sent with, the later base moves too, also after a reload and when another tab took the
  queue over (both the record and the base are stored with the call). Without a record on both calls the
  library cannot know that the two concern the same record, and the later call goes out on its old base and
  conflicts with the user's own edit: a needless conflict, which the resolver or the user settles, rather than
  overwriting someone else's change. The demo's tasks declare `record` on every action.
- **Resends keep their base.** Once a call was pushed, its base no longer moves: delivery is at least once,
  the server may have applied the first push, and the retry must look like the same call. That is why the
  handler checks the processed ids before the version.
- **Multiple tabs.** The settlement announcement carries the conflict, the server's state and any
  resubmission, so the tab that made the call settles it the same way (its promise follows the resubmitted
  call) while only the tab that got the reply runs the resolver.

## Conflicts that wait for a person

A resolver decides at once. When a person must choose between their change and the server's, park the call
instead:

```js
renameTask: {
  apply, server: "rename_task", base, record: (id) => ["task", id],
  onConflict: "park", // or a resolver that returns "park", or a promise of { args } / null
},

tasks.onConflict(({ id, args, parked }) => {
  if (parked) showChoice(id, args, parked.reason, parked.state); // the person's change, and the server's values
});
tasks.pending(); // [{ id, action, server, args, base, record, parked: { reason, state } }, { ..., blocked: true }]

// Later, when the person chose:
tasks.resolveConflict(id, "mine"); // send my change again, on the version the server holds now
tasks.resolveConflict(id, "mine", { args: ["t1", merged] }); // or send other arguments, such as a merge
tasks.resolveConflict(id, "theirs"); // keep the server's values
```

- **Parked.** The call is rolled back (the server's `state` is merged and shows), keeps its place in the queue
  and is not sent. Its promise waits. `pending()` lists it with `parked: { reason, state }`, and `onConflict`
  listeners receive it with `parked` (no `onSettled`: it is not settled). It blocks later calls that may concern
  the same record (the same `record`, or either declares none), listed with `blocked: true`; calls of other
  records go on.
- **Persisted and shared.** The parked call is stored with the queue, with the reason and the server's state, so
  a reload restores it parked (announced through `onPending` with `parked`). Parking and resolving are announced
  to the other tabs; the call can be resolved in any tab that holds it.
- **`resolveConflict(id, "mine", { args? })`** sends the call again, with the given arguments or its own. The
  server receives a **new `meta.id`**: it already answered the old id with a conflict, and a handler that looks
  ids up first would answer the same id with the same conflict. The base is evaluated on the confirmed state
  now, so it holds the version the server sent. The new call takes the old one's place in the queue, the promise
  of the original call settles with its outcome, and `onSettled` reports the old id as `"resubmitted"` with
  `resubmittedAs`. Later calls of the same record, never sent and based on the same version as the parked one,
  get their base moved too: the person kept their change, and their next edits build on it.
- **`resolveConflict(id, "theirs")`** drops the call: its promise rejects with `{ conflict: true, reason, state }`
  and `onRejected` and `onSettled` report it as a conflict, as when a resolver gives up. Values that arrived
  since it was parked are kept.
- `resolveConflict` returns `false` for an id that is not parked and throws for another choice or `args` that
  are not an array. A parked call cannot be cancelled (it was sent); resolve it.
- **A resolver that returns a promise** parks the call until the promise settles: `{ args }` keeps mine with
  those arguments, `null` keeps theirs, a rejection keeps theirs and is reported with `console.error`. An answer
  that arrives after the call was resolved by hand is ignored, and after a reload the promise is gone: the call
  waits for `resolveConflict`. A resolver may also return `"park"` for some conflicts and `{ args }` for others.
- `maxResubmits` limits a resolver's automatic resubmissions only; `"park"` and the person's `"mine"` are not
  counted.

What this does not do: it never merges two edits. A conflict is resolved by the server's state, and by a
resolver that decides to send the call again on top of it; merging the user's change with the other one is
the application's choice, in the resolver or in the handler. Data that several people edit at once and that
should merge automatically, also after offline edits, is what collaborative keys are for (see
[Collaborative keys](collaborative-keys.md)).
