# Models

`model`: a schema that is also the calls that read and write it. A model is
declared once; the declaration gives a type, a table, and typed operations
(`find`, `add`, `set`, `del`, …), kept in this browser (`local model`) or on
the back end (`model`), where rules say who may do what. Back to the
[map](README.md).

```mote
// docs: whole
local model Note
  title: string
  body: string = ""
  done: bool = false
  changed: time = now always
  index changed
  check title.trim() != "" else "a note needs a title"

state draft = ""

resource notes: Note[] = Note.find({done: false}, {order: "changed desc"}) else []

action add
  Note.add({title: draft})?
  draft = ""

action finish(id: string)
  Note.set(id, {done: true})?

column gap=8 padding=16
  row gap=8
    input value=draft placeholder="A note" submit=add
    button "Add" press=add
  text (failure(add) ?? "") color=danger
  for n in notes key=n.id
    row gap=8
      text n.title flex=1
      button "Done" press=finish(n.id)
```

No SQL, no back end, no `refresh`: the list is a resource over a find, and it
runs again when the page writes a row that find could give.

## Mental model

- **A model is a shape that is kept.** `Note` is a type wherever a shape's
  name may stand (`Note[]`, a parameter, a prop), and one SQLite table named
  `Note`.
- **Where it is kept is the word before it.**

  | Written | Kept | The page reaches it by | A `server fn` reaches it by |
  |---|---|---|---|
  | `local model T` | this browser: SQLite in the page's worker, the database `app` in the site's private files ([data.md](data.md#sql)) | a call into the page's own SQLite, no network | not at all (`H113`) |
  | `model T` | the back end: `app.sqlite` in its data folder, or Postgres ([`MOTE_SQL=postgres://…`](back-end.md#models-in-postgres)) | a typed call, `POST /rpc/T.find`, checked by the model's rules | the same operations, in its own process, not checked by rules |

  A program may have both kinds. They never meet in one query; a page joins
  them itself. (`synced model` is reserved.)
- **One engine, two places.** An operation (`find`, a filter, options) is
  turned into SQL with parameters by one part of the runtime
  (`runtime/shared/model.mote`). The page runs it on its SQLite; the back
  end on Bun's. Nothing a caller gives is ever part of the SQL's text: every
  name in it is the schema's own, every value a parameter.
- **Every operation waits and can fail**, like any call that leaves the
  page: settle it with `?` or `else`, load it with a `resource`
  ([language.md](language.md#a-call-that-can-fail)). So it cannot stand in a
  `derive` or a binding (`H082`).
- **A page's write of one row to a `model` shows at once.** `T.add`,
  `T.set` and `T.del` put the row the page expects in its `live` values and
  go on; the back end's answer takes its place, and a refusal takes it back
  ([below](#a-write-shows-at-once)). `confirmed` says "wait" instead.
- **A program with only `local model`s has no back end** and works offline.
  One `model` makes a back end ([back-end.md](back-end.md)).

## Declaring a model

`model Name` or `local model Name`, at the top of the entry file or of any
file it `use`s (by habit, `schema.mote`), with its lines indented under it.
A model's name starts with a capital. It is declared once in the program,
and no shape has it (`H022`, with both places); a component may (a tag and
a model are told apart by where they stand: `model Command` beside the
kit's `Command`, in the page and on the back end alike: in a `server fn`, a
hook, a type, `Command` is the model).

**Fields** are `name: type` lines, as in a shape, with what a kept thing needs:

| Form | Meaning |
|---|---|
| `id: id` | The key: text, made (a UUID) when a row is added without one. A model with no key line gets exactly this one. |
| `slug: string key` | Another field as the key (text or a number). It is given when adding. |
| `id: id = me` | A key that is who is signed in: one row a person. |
| `title: string` | Must be given when adding. |
| `body: string = ""` | A default: may be left out when adding. A default is a value written out (`""`, `0`, `false`, `[]`, `{…}`), `now` or `me`. |
| `at: time = now` | `time` is a number of milliseconds; `= now` is the moment the row is added. `= now always` is set again on every change. |
| `owner: User = me` | A reference: another model's row, kept as its key (so `owner` is a `string` in the row). `= me` is the id of who is signed in, **filled by the back end and never given by the page**. |
| `note: string?` | May be none. |
| `tags: string[]`, `place: {lat: number, lon: number}`, a shape, `json` | Kept as JSON; typed on the way in and out. Cannot be filtered or ordered on. |
| `data: bytes` | A blob, kept in the row and sent with it. |
| `photo: file` | A file: its bytes in the data folder, `{id, name, type, size, url}` in the row ([below](#files)). `model` only. |
| `email: string unique` | No two rows the same: a second fails with the kind `"taken"` ([a create that loses](back-end.md#a-create-that-loses-taken)). |
| `room: Room cascade` | When the room is removed, so are these rows. `restrict` (the default) refuses to remove a room that has them; `clear` sets a `Room?` to none. |
| `secret: string hidden` | Never sent to the page, and the page cannot filter, order on, or give it: not by the model's operations, and not in what a `server fn` returns ([below](#what-a-server-fn-returns)). In the row's type it is `string?`, since a page never has it. |
| `who: Member = me private` | Whose the row is, kept from everyone else: the page of the person it names is given it, any other page `none` ([below](#a-private-field)). In the row's type it is `string?`. |
| `subject: string was title` | A rename ([below](#changing-a-schema)). |

Types to columns: `string`, `id` and references TEXT · `number` REAL · `int`
and `time` INTEGER · `bool` INTEGER · lists, records and `json` TEXT (JSON) ·
`bytes` BLOB. The same in both places.

**Lines of the model itself:**

| Form | Meaning |
|---|---|
| `unique room, user` | No two rows with the same pair. |
| `index room, at` | An index, for the finds that filter or order by those fields. (Each reference gets one of its own.) |
| `index text, title fulltext` | An index of the words in those fields, for `T.search` ([below](#full-text-search)). One a model; `string` fields that are neither `hidden` nor `private`. |
| `check kind in ["text", "todo"]` | The same, with a rule's `in`: one of the values listed. |
| `check text.trim() != ""` | Must hold for every row added or changed. It reads the row's fields, and nothing else of the program. `else "what to tell the person"` gives the failure's words. For a model on the back end it is tried in the page first, on the fields the page gives, and on the back end always. |
| `read`, `add`, `change`, `remove`, `write` + `anyone` or `if test` | A rule ([below](#rules)): `model` only. |
| `was OldName`, `dropped field` | A rename; a field whose data may go ([below](#changing-a-schema)). |

## The operations

Every model has these, typed from its fields.

| Call | Gives | |
|---|---|---|
| `T.get(key)` | `T?` | none if there is no such row (or the page may not read it) |
| `T.one(filter)` | `T?` | the first match |
| `T.find(filter, options)` | `T[]` | both may be left out: `T.find()` is every row |
| `T.count(filter)` · `T.has(filter)` | `number` · `bool` | |
| `T.search(words, filter, options)` · `T.searchCount(words, filter)` | `{…T, rank, snippet}[]` · `number` | in a model with `index … fulltext` ([below](#full-text-search)) |
| `T.add(row)` | `T` | the row as kept: key, defaults and `me` filled in |
| `T.addAll(rows)` | `T[]` | all or none |
| `T.set(key, changes)` | `T` | only the fields given change; fails if there is no such row |
| `T.setAll(filter, changes)` | `number` | how many changed |
| `T.take(filter, changes, {order})` | `T?` | the first row the filter finds, changed: or none ([a queue](#a-queue-the-page-never-sees)) |
| `T.put(row, changes)` | `T` | the row there by its key or a `unique` set, changed by `changes` (unsaid: by the row's other fields); none there, `row` is added ([below](#put-and-inc)) |
| `T.del(key)` · `T.del(filter)` | `number` | how many went; `T.del({})` is every row |
| `T.count(filter, {by})` · `T.sum(filter, field, {by})` · `T.min` · `T.max` | `{…, count}[]` · `number` | rows taken together, the back end's alone ([below](#rows-taken-together)) |

In a change, `inc(n)` adds to a number: `T.set(key, {n: inc(1)})`, `T.setAll(filter, {left: inc(-1)})` ([below](#put-and-inc)).

**A filter** is a record of the model's fields; several fields are "and":

```text
{room: id}                          equal
{state: ["open", "held"]}           any of a list
{note: none}                        none
{at: after(t)}  {at: before(t)}     greater, less: numbers, times, text
{at: between(a, b)}                 from a to b, both included
{name: startsWith("ab")}            text; the case counts
{room: id, any: [{thread: none}, {shown: true}]}
                                    one of several filters, and the fields beside them
```

`any: [filter, filter]` is the one "or" there is: a row passes when it
passes one of the filters in the list (each a record of fields, as above;
twenty at most, none with an `any` of its own), and the fields written
beside it. The model's `read` rule is around the whole of it. There is no
"not" and no looking inside JSON: anything richer is `.filter(…)` on what
comes back, or a `server fn` with `sql.run` over the same table. (Words
inside a text are not a filter: that is [`T.search`](#full-text-search).) (In a model
that has a field called `any`, the word is that field.) The words `after`, `before`, `between` and
`startsWith` stand only as a filter's values (`H064` elsewhere).

**The options** of `find`:

| Option | |
|---|---|
| `order: "at"` · `order: "at desc"` | By a field. Rows equal in it, and all rows with no order, come as they were added. |
| `limit: 20` | The first twenty in the order. |
| `after: row` or `after: key` | Only the rows after that one, in the order: with `limit`, a next page that holds while rows arrive. |
| `last: 50` | The newest fifty in the order, oldest first: what a feed wants. |
| `with: ["from"]` | Follows references one step: `from` is the `User` row (or none) and not its key. The names are written out, since the type of what comes back depends on them: `{…, from: User?}`. |

```mote
// docs: whole
local model Author
  name: string unique

local model Book
  title: string
  author: Author cascade
  year: int = 2000
  index year

state said: string[] = []

task show
  let ada = Author.one({name: "Ada"})? ?? Author.add({name: "Ada"})?
  if Book.count({author: ada.id})? == 0
    Book.addAll([{title: "Notes", author: ada.id, year: 1843}, {title: "Letters", author: ada.id}])?
  let old = Book.find({year: before(1900)}, {order: "year", with: ["author"]})?
  said = old.map(b => `${b.title} by ${b.author?.name ?? "?"}`)
  let first = Book.find({}, {order: "title", limit: 1})?
  let next = Book.find({}, {order: "title", limit: 1, after: first.at(-1)})?
  said.push(`then ${next.map(b => b.title).join(", ")}`)

for line in said
  text line
```

- `T.add(row)?.id`: after a call that can fail, `?.` is its `?` and then the
  `.`. `T.count({})? == 0` is the `?` and then the comparison.
- A reference must point at a row that is there (`there is no such Author
  for Book.author`). References are kept by the engine, not as SQL foreign
  keys: `sql.run` around a model is on its own.

### put and inc

A counter is a row that is added the first time and added to after. `put`
is both, and `inc(n)` is "this much more than it is":

```mote
// docs: whole
model Tally
  slug: string key
  day: string
  hits: int = 0
  ms: number = 0
  read anyone

model Vote
  poll: string
  who: id = me
  choice: string
  unique poll, who
  read anyone
  add if me != none
  change choice if who == me

server fn hit(slug: string, day: string, ms: number): Tally requires anyone
  return Tally.put({slug, day, hits: 1, ms}, {hits: inc(1), ms: inc(ms)})?

server fn tidy(day: string): number requires signedIn
  return Tally.setAll({day}, {hits: inc(-1)})?

action vote(choice: string)
  Vote.put({poll: "lunch", choice}) else none

column gap=8 padding=16
  button "Soup" press=vote("soup")
  button "Salad" press=vote("salad")
```

- **Which row.** The row's key, where the row gives it; else the first set
  that may not repeat (`slug: string unique`, a line `unique poll, who`)
  whose fields it gives, counting what the engine fills in: `who: id = me`
  is the caller, so `Vote.put({poll, choice})` is each person's own vote. A
  row that names none of them is refused when compiled (`H164`, with the
  sets it could give).
- **What happens** is an add or a change, and is that to everything after:
  there, the row is changed by `changes` (unsaid: by those of the row's own
  fields that differ, its key and the set it was found by left alone); not
  there, `row` is added, defaults and all. The rules are the add's
  (`add if …`) or the change's (`change … if …`), the hooks are `server
  before/after T.add` or `T.change(was, now)`, the checks run on the row as
  it would be kept, and a page holding the row in a `live` value is sent it
  as an added or a changed row. A page may `put` where the model has both an
  `add` and a `change` rule (`H112` names the one missing); a row there that
  the page may not read is refused, as adding it would be.
- **One turn.** The look and the write stand in one turn of the database (a
  write transaction, `BEGIN IMMEDIATE`, which another back end at the same
  database waits for): two callers never both add the row. Where nothing
  needs to see the row first (the back end's own code, a change that is
  only `inc`, no `change` hook, no check), the change is one statement:
  `UPDATE … SET hits = hits + ? … RETURNING`; where that finds no row, the
  row is added.
- **`inc(n)`** stands for a field's value in the changes of `set`,
  `setAll`, `take` and `put`: `n = n + ?` in SQL, on a `number`, `int` or
  `time` field (none counts as 0). The row a write gives back, the hooks'
  `now`, the checks and what a page is sent are of the result. Anywhere
  else, or on a field that is not a number, it is refused (`H164`).
- **From a page** a `set` with `inc` shows at once like any `set`: the row
  the page holds, with `n` added. A `put` waits for the back end (the page
  cannot know whether the row is there, and so which it will be), as if it
  were written `confirmed`.

### Rows taken together

How many rows there are of each kind, and what a field of them adds up to,
asked of the database rather than read row by row:

```mote
// docs: whole
model Sale
  day: string
  shop: string
  total: number
  items: int = 1
  read anyone

shape ShopDay
  shop: string
  total: number
  items: number

server fn byShop(day: string): ShopDay[] requires signedIn
  return Sale.sum({day}, ["total", "items"], {by: ["shop"], order: "total desc", limit: 20})?

server fn kinds(): number requires signedIn
  let counts = Sale.count({}, {by: ["shop", "day"]})?
  let biggest = Sale.max({}, "total")?
  return counts.length + (biggest ?? 0)

action look
  let rows = byShop("2026-11-20") else []
  log(rows)

button "Look" press=look
```

- **`T.count(filter, {by: ["field", …]})`**: `[{field: value, …, count}]`,
  a record for each different set of values, with how many rows have it.
  **`T.sum(filter, "field", {by})`**: the same with the field's total in
  place of `count`; a list of fields (`["total", "items"]`) is each one's.
  **`T.min`, `T.max`** likewise (a number, a time or a text). Without `by`
  (and of one field) each is one value: `T.sum({day}, "total")` is a number,
  `T.max({}, "at")` the latest time or none.
- **`order`**: a field it groups by, or what it gives (`"count desc"`,
  `"total desc"`), then the groups in order. **`limit`**: 1000 groups unless
  said, 10000 at most. `by` names 8 fields at most, written out (the type of
  what comes back is made from them); a field that holds a record or bytes
  is neither grouped by nor added up.
- **The back end's alone.** In a page (and on a test's lines) it is refused
  (`H165`): a page reads rows. In a `server fn`, `T.as(me).count(f, {by})`
  asks it as the caller's page would: the `read` rule is in the statement's
  WHERE, so a row the caller may not read is in no group, and what is hidden
  or private is neither grouped by nor added up.
- It is one statement (`SELECT shop, coalesce(sum(total), 0) … GROUP BY shop
  ORDER BY … LIMIT 20`), with the filter as `find` has it. There are no
  joins and no aggregate in a filter: a richer question is `sql.run` over the
  same tables.

### atomic

```text
atomic
  let c = Card.get(id)?
  Column.set(to, {count: n + 1})?
  Card.set(id, {column: to})?
```

`atomic` + a block makes the operations in it one: all kept when the block
ends (or returns), none if anything in it fails. It goes where something can
wait: an action, a fn, a task, a handler. In the page it
joins operations on local models, written in the block itself (a fn that
waits cannot be called inside it); on the back end it is the database's
transaction, and fns called inside it stand in it too.

**Writes wait their turn**: one write, or one `atomic` block, at a time.
While a block runs, every other write and every other block queues, in the
order they came. In the page, reads take their turn with them.

**On the back end a read does not wait for a write.** A read (`get`, `one`,
`find`, `count`, `has`) that stands in no block is answered from the last
state that was kept, while a block is still running:

- **It sees what was kept when it began, and all of one moment**: a `find`,
  the rows its `with` follows and what its `read` rule looks into are one
  snapshot. Two reads are two moments.
- **It never sees a write that is not kept yet**: not the half of a block
  that is still running, and nothing of one that fails.
- **A call reads its own writes**: a write is kept before its `?` gives its
  answer, so the line after `T.add(row)?` finds the row, and so does every
  caller from then on.
- **Inside `atomic`, a read is part of the block**: it sees what the block
  has written so far (which nobody else does yet), and so do the fns called
  inside it and a `before` hook. Reads that must agree with each other, or
  with a write that follows them ("if there is none, add one"), go in
  `atomic`: there they take a turn among the writes.
- **A `live` value is worked out after the write that touched it is kept**:
  a page is never sent what a block might still undo.

So a block that waits (on `net`, on another program) holds up the writes
behind it, and no read. Recorded, with a block that waits a second and a
half, in `tests/expect/real_engine_scale.txt`.

**So nothing but the data waits inside `atomic`, on the back end.** `mote
check` warns of a block that waits on anything else (`H144`: a request, a
program, a battery, another back end, `detach`), in the block or in a fn it
calls. What must follow the block's writes, and only if they are kept, is a
[`job fn`](back-end.md#later-job-fn) queued inside it: the job is a row,
written in the block's turn, and is run once the block is kept
([back-end.md](back-end.md#nothing-but-the-data-waits-inside-atomic)).

## Local models

- The data is the browser's own, whoever is signed in: no rules, no hooks,
  no `me`, nothing `hidden` (`H110`).
- **A `resource` over a read follows the page's writes.** It runs again when
  a row is added, changed or removed that its filter matches (before or
  after the change), or when a model its `with` follows is written. A write
  to another model, or to rows the filter does not match, does not run it.
- A `derive` cannot read a model (it never waits): use a `resource`.
- The tables are in the database `sql.open("app")` gives the page, so
  `sql.run` can read them. A write made that way tells no resource.
- **Every window of the origin has the same rows.** Two tabs of the app
  share the database ([data.md](data.md#sql)): each reads what the other
  wrote, and **a write in one runs the others' resources again** just as
  it runs its own (the rows that changed are told to the other windows,
  and each works out which of its reads they touch). A write made around
  the models with `sql.run` tells no window.

## Models on the back end

```mote
// docs: whole
model Member
  id: id = me
  name: string
  read anyone
  add if me != none
  change if id == me

model Room
  name: string unique
  owner: Member = me
  read anyone
  add if me != none
  change, remove if owner == me

model Message
  room: Room cascade
  from: Member = me
  text: string
  at: time = now
  index room, at
  check text.trim() != "" && text.length <= 4000 else "say something (4000 letters at most)"
  read anyone
  add if exists(Member, {id: me})
  change if from == me then from == me
  remove if from == me

state email = ""
state password = ""
state room = ""
state text = ""

live rooms: Room[] = Room.find({}, {order: "name"}) else []
live messages = Message.find({room: room}, {order: "at", last: 50, with: ["from"]}) else []

action join
  auth.signUp(email, password)?
  Member.add({name: email.split("@")[0]})?

action open(name: string)
  let r = Room.one({name})? ?? Room.add({name})?
  room = r.id

action send
  Message.add({room: room, text: text})?
  text = ""

column gap=8 padding=16
  row gap=8
    input value=email type=email placeholder="Email"
    input value=password type=password placeholder="Password"
    button "Join" press=join
  row gap=8
    for r in rooms key=r.id
      button r.name press={room = r.id}
    button "Open the den" press=open("den")
  for m in messages key=m.id
    text `${m.from?.name ?? "someone"}: ${m.text}`
  input value=text submit=send placeholder="Say something"
  text (failure(send) ?? failure(join) ?? failure(open) ?? "") color=danger
```

No `server fn`, no SQL, no `changed(…)`.

- From the page, `Message.find(f, o)` is `POST /rpc/Message.find` with
  `[f, o]`: a typed call like a `server fn`'s. What arrives is checked
  against types the model gives before anything runs: an unknown field, a
  wrong type, an option that is not there are refused (400).
- **A page is given 1000 rows at most by a `find` that names no `limit`**
  (or `last`), the first thousand in its order: a list that can grow past
  that is paged (`limit` with `after`), or asked for with a `limit` of its
  own, which may be 10000 at most. A larger one is refused (`T.find gives
  the page 10000 rows at most at a time`), and so is a filter's list of more
  than 1000 values (`{id: ids}`): failures the page settles, not faults.
  `count` counts them all. The back end's own code (a `server fn`, a hook)
  is given whatever it asks for.
- **`live x = T.find(…)`** (or `get`, `one`, `count`, `has`) keeps the value
  current. Every write to the model says which rows changed; the back end
  works out which kept values a row could be in (its filter against the row
  before and after; a model its `read` rule looks into, or its `with`
  follows) and brings those up to date: by sending the page the row that
  changed, where that is enough, else by working the read out again
  ([what a write sends a page](#what-a-write-sends-a-page)). A page is sent
  nothing of a row it may not read. `changed(…)` is never written for a model.
- **A write from the page shows at once**: `send` above clears the field
  and the message is in the list before the back end has answered
  ([below](#a-write-shows-at-once)).
- `me` is the id of who is signed in on this call (`auth`,
  [back-end.md](back-end.md#signing-in)), or none. A model whose key is
  `id: id = me` is the usual way to keep who a person is; a reference
  `= me` then points at their row, so it must be there before they write.
- When several apps [share their accounts](back-end.md#accounts-several-apps-share),
  `me` is the same id in every one of them, so `= me` fields line up across
  the apps. The models do not: each app has its own database, and so its
  own `Member` row about the person (accounts are shared, each app keeps
  its own row), made the first time they come to that app.

### What a write sends a page

Nothing here is written in a program: `live msgs = Message.find(…)` is all
there is to say. This is what the runtime does with it, for whoever is
sizing an app or reading the line.

A page that keeps `Message.find({channel: room}, {order: "at", last: 50})`
is sent the list once, when it asks. After that a write to `Message` sends
it **the row**, not the list: a few hundred bytes for a message added to a
channel of any length, and no query. The page's runtime puts the row in the
list it holds, at the place the order gives, keeps the list to its `last`
or `limit`, and a keyed `for` over it draws that one row: the others are
not touched.

| The write | What a page that keeps a read of the model is sent |
|---|---|
| a row added that the read finds | the row |
| a row changed, still found | the row; it moves if what orders the list changed |
| a row changed so that the filter (or the `read` rule) now finds it, or no longer does | the row, or only its key: "have none of this" |
| a row removed | its key |
| `count` | the new number; `has`: `true`, when a row comes to be found |
| a row this person may not read, before and after | nothing |

Each reader's row goes through all that running the read again would put
it through: the model's `read` rule as that person (from the row itself
where the rule is about its fields and `me`; where it says `exists(…)` or
reads a reference's field, the row is read again by its key as that
person: one small query), `hidden` fields left out, a `private` field
given only to whom it names, the read's filter before and after the write.

**The read is run again, as it always was, wherever a row alone does not
say what it now gives:**

- a row of *another* model changed: one the `read` rule looks into, or one
  `with` follows;
- one turn changed many rows (more than eight: an `atomic` block, `addAll`,
  `setAll`, a `del` by filter, a cascade), or the write was made around the
  model and told with `changed("Message")`;
- a row left a list that was full (`limit`, `last`, or the thousand rows a
  page is given at most): the row that takes its place is the database's to
  say. Likewise a row that comes to stand equal, in the order, to rows
  already there, and a row that comes into a list with no `order` by a
  change;
- `has`, when the row it found may have been the last; a `search`; a
  `find` with `after:`; a filter on a `private` field; a model whose `read`
  rule looks into the model itself; a `server live fn` (program code);
- the line dropped and opened again: every value is asked for whole. So
  too after the back end said it was going
  ([stopping](back-end.md#health-and-stopping)): the page asks the next one
  for the value whole, and is sent rows after. A back end that is stopping
  works out no more rows: what the calls it is still answering change is
  read again for the pages still on its line;
- the rows could not be worked out (anything going wrong on the way): the
  read is run again, and [the log](back-end.md#logs) says so in a line at
  `debug` (`msg: "rows"`). If the read breaks too, that is a fault as for
  any `live` value: the page is told `… could not be done (id …)`, the log
  has it (`where: "live"`), and `server on failure` hears it. A row sent
  is no line in the log.

So an app is sized by its common write: a chat's new message is one row to
each open page. `mote check --perf` names the `live` lists that have no
`limit` or `last`, which are sent whole (a thousand rows at most) when a
page first asks.

- **What the page holds is what running the read again would give.** To
  see it checked, start the back end with `MOTE_ROWS_CHECK=1`: after each
  row it sends, it also runs the read and sends a number for the whole
  value, and a page that holds anything else says so on its console and
  asks for the value again. `MOTE_ROWS=0` turns rows off altogether
  ([internals.md](internals.md#rows-not-lists)).
- With [several apps at one database](back-end.md#a-write-in-one-app-reaches-the-others-pages)
  a row another app wrote is sent the same way, read again by its key
  first.
- Something else that opens the line (a script, a test) is sent whole
  values unless it says it takes rows ([the wire](back-end.md#the-wire)).

Recorded: `tests/expect/real_live_rows.txt` (every kind of read, two
browsers, each value held against a fresh read), `real_live_rules.txt`
(every frame three people's sockets were sent), `real_live_shared.txt`.

### A write shows at once

`Message.add(row)`, `T.set(key, changes)` and `T.del(key)`, written in a
page for a `model` the back end keeps, do not wait for the back end before
the page shows them. Nothing is written for it:

```mote
// docs: whole
model Message
  room: string
  text: string
  at: time = now
  check text.trim() != "" else "say something"
  read anyone
  add anyone
  change anyone
  remove anyone

state draft = ""
live messages: Message[] = Message.find({room: "den"}, {order: "at", last: 50}) else []

action send
  Message.add({room: "den", text: draft})?
  draft = ""

action reword(m: Message)
  Message.set(m.id, {text: `${m.text}!`}) else err => toast("Not changed", err, "error")

watch failure(send)
  let why = failure(send)
  if why toast("Not sent", why, "error")

column gap=8 padding=16
  for m in messages key=m.id
    row gap=8 opacity=(pending(m) ? 0.5 : 1)
      text m.text
      button "!" press=reword(m)
      button "Remove" press={Message.del(m.id)?}
  input value=draft submit=send placeholder="Say something"
```

On a line where the back end is half a second away, the message is in the
list in the frame of the key that sent it, dimmed; the field is empty at
once; half a second later the row is no longer dimmed, and it is the same
row (the same node: a caret in it stays where it was).

**What the page does.** It works out the row the back end will keep, puts
it in every `live` value on the page it belongs in, and sends the write.

| Of the row | The page says |
|---|---|
| the key (`id: id`) | made in the page (a UUID, as the back end would make one) and sent: the back end keeps the row under it, so the row the page shows and the row that is kept are one row from the start. A key the page gave (`slug: string key`) is that one. |
| `= now` | the page's clock; the back end's own time takes its place when the answer arrives |
| `= me` | who is signed in (the open line tells the page when it opens) |
| a default, a field given | as declared, as given |
| `hidden` fields | not in a row the page has, as ever |
| `check` lines | tried in the page first, as they always were: a row that fails one is never shown, and nothing is sent |

| The write | In the `live` values on the page |
|---|---|
| `add` | the row goes in each `find`, `one` and `get` whose filter it passes, at the place the order gives, kept to the `limit` or `last`; a `count` whose filter it passes goes up; a `has` becomes true |
| `set` | the fields given change in the row wherever the page holds it; it moves if what orders the list changed, and leaves or enters a list by its filter |
| `del` | the row goes from wherever the page holds it |
| in a `find` with `with: […]` | shown where the page already holds the rows the references point at (in another list, or beside another row of the same list); else that list waits for the back end's row |
| in a `find` with `after: …` | a row already in the list changes and goes as above; a row new to it waits for the back end, which knows whether it comes after that one |
| in a list that is full (`limit`, `last`) | a row that leaves it goes at once, and the row that takes its place arrives with the answer; a row that moves to its open end shows its new values where it stands until then |

- **The call gives the row at once**, and the action goes on: `draft = ""`
  above happens in the same breath. `let m = Message.add(row)?` is the row
  the page expects (its key is the real one). `T.del(key)` gives 1.
- **`pending(row)`** is true of a row with a write the back end has not
  answered yet. It is reactive: `opacity=(pending(m) ? 0.5 : 1)`.
  `pending(action)` means what it did (a run is in flight), which for an
  action that only writes is now over at once: dim the row, not the button.
  The kit's components do nothing with it by themselves.
- **When the answer arrives** the back end's row takes the place of the
  page's (same key: a keyed `for` keeps the node, and nothing flickers).
  The same row also arrives on the open line, before the answer or after
  it; either way it is put on the same key.
- **Writes are sent one at a time, in the order they were made**, and every
  other call the page makes waits for the writes made before it: the back
  end hears a page's calls in the order the program made them. A second
  write to a row waits behind the first (two quick toggles show the second
  state, and never flick back to the first). A row added and removed before
  its `add` was sent: neither is sent.

**When the back end refuses it** (a rule the page cannot ask, a `unique`
name taken by a row the page does not hold, a `before` hook that fails):

1. The change is taken back: an added row goes, a changed row has its old
   values again, a removed row is back in its place. (The values that held
   it are then asked for whole, so that the page ends with what the back
   end has, whatever else happened meanwhile.)
2. The failure goes to whoever was to hear it: the `else` written beside
   the write runs (`reword` above); with `?`, the action the write stands in
   has it (`failure(send)`, with its `kind` and `data`: `"taken"` and
   `{model, fields}` for a `unique` value another row has), and if nothing
   reads that action's failure, `on failure` hears it.
3. **Nothing else the action did after that line is undone.** `send` above
   has cleared the draft by the time the refusal arrives, and it stays
   cleared. Where that matters, say what to do in the `else` (put the words
   back, as `tests/refused_writes` does), or show the failure
   (`watch failure(send)`, a toast). The value an `else` gives when it runs
   late is not used: the action has gone on with the row.

A row whose writer may not read it (a `read` rule the row does not pass)
is taken back without a failure when the answer says so: the write was
made, and no `live` value of theirs would hold it.

**While nothing answers** (`net.online` is false, or the call got no answer
after its [tries](back-end.md#a-call-is-answered-once)), a write is kept,
not failed: the row stays, `pending`, and the writes go when the line is
back, in the order made, each still made once. Two hundred writes are kept
at most, for five minutes at most; past that they fail as `"offline"` (`could not reach the server: it was not sent`) and
are taken back. They are kept in the page only: a page that is closed or
loaded again loses them. A call to a `server fn` is not kept: it fails.
(A write that is given up on may have reached the back end all the same,
its answer lost: the page then says it failed and, when the line is back
and every `live` value is asked for again, shows what the back end has.)

**`confirmed`: a write that waits.** Where a wrong picture for half a
second matters (money, stock), say so:

| Said | Means |
|---|---|
| nothing | writes of a model from the page show at once |
| `confirmed Order.add(row)?` | this write waits for the back end before anything shows, and the action waits with it |
| `confirmed`, a line of a `model` | every write of that model from the page waits |
| `app "Shop" writes=confirmed` | every write in the program waits, as all did before |

```mote
// docs: whole
model Order
  what: string
  at: time = now
  confirmed
  read anyone
  add anyone

model Note
  text: string
  read anyone
  add anyone

state what = ""
live orders: Order[] = Order.find({}, {order: "at"}) else []

action place
  Order.add({what})?
  confirmed Note.add({text: `ordered ${what}`})?
  what = ""

column gap=8 padding=16
  input value=what submit=place
  button "Order" press=place disabled=pending(place)
  for o in orders key=o.id
    text o.what
```

**These wait by themselves**, with nothing said, because the page cannot
say soundly what the back end will keep (each behaves exactly as writes did
before):

- `addAll`, `setAll`, `take`, and a `del` by a filter: many rows, or rows
  the page cannot name.
- A write that gives a `file`: the back end makes the row's file of it.
- A model one of whose `check` lines the page cannot try (it reads a
  `hidden` field), or whose key the page is not given.
- A `set` or a `del` of a row the page holds in no `live` value: there is
  nothing to show, and nothing to put back.
- A row with a `= me` field before the page knows who is signed in (in the
  moment after signing in, while the line opens again).
- A write in a `fn` that passes its failure on with `?`: the failure is the
  fn's caller's to settle, so the caller waits for it. (With an `else` of
  its own, the write shows at once.)
- A write whose row the action goes on to use (`let c = Channel.add(row)?`,
  then `c.name`), of a model with a `server before` hook for that write:
  the hook may change the row, and only the back end knows to what. Without
  such a hook, or where the row is not used, it shows at once; what a
  `before` hook changed in a row then shows when the answer arrives.
- A `resource` that reads a model is not kept by writes at all, as before:
  `refresh(it)` after the write (which waits for the write, like any call).
- A `local model`'s writes are the page's own and were always at once; a
  write in a `server fn` is a write. A call to a `server fn` is not shown
  ahead: the page cannot know what it will do. What it writes reaches the
  page's `live` values as rows, as soon as it has written them.

Recorded: `tests/expect/real_instant_writes.txt` (the frame a row shows in, its
node kept, two browsers, the row's message before the answer and after),
`real_refused_writes.txt`, `real_offline_writes.txt`, `real_answered_once.txt`.

### A long list, a window at a time

A `live` read is the whole read, kept by its rows ([above](#what-a-write-sends-a-page)),
and a page is given a thousand rows of it at most (ten thousand with a `limit`). A list
longer than that, or a long one opened often, is kept **a window at a time**: the read
says `window`, and its list is drawn by a [`for … virtual`](markup.md#long-lists).

```mote
// docs: whole
model Order
  number: int key
  customer: string
  placed: time = now
  index placed
  read anyone
  add anyone

live orders = Order.find({}, {order: "placed desc", window: 200}) else []

column gap=8 padding=16
  text `${orders.length} orders`
  column height=480 overflow-y=auto
    for o in orders key=o?.number virtual=36
      if o
        row height=36 gap=12 align-items=center
          text `#${o.number}` width=80
          text o.customer
      else
        row height=36 align-items=center color=dim
          text "…"
```

- **The value** is a list as long as the read's count (`orders.length`), holding the
  rows of the windows the page holds and `none` at every other place. Its type is
  `Order?[]`: a row's field is `o?.customer`, the key is `key=o?.number`, and a place not
  come yet is drawn by the `else`. The page is sent the count and the first window when it
  asks.
- **Which windows.** A `for … virtual` over the value tells it which rows it draws (those
  in view, and a screenful and more around them), and the page asks for the windows those
  need, half a window more on each side: 80 ms after the rows drawn last changed, and every
  300 ms while they go on changing, so a list flung far asks on the way and where it stops.
  Windows no longer wanted are let go of, and the back end no longer follows their rows: a
  page holds the few around its view.
- **By key, not by offset.** A window is "the rows after this one": by the order's field and
  then the key, so no two rows stand equal (rows with the same `placed` come by `number`, in
  the read's way). A window holds its rows while others come and go around it; a row's place
  in the list is its place in the order, and the back end keeps each held row's place right
  as rows arrive above it.
- **Rows that come and go**, from this page or any other, each worked out for its reader
  under the model's `read` rule, as for any read:

  | The write | What the page is sent |
  |---|---|
  | a row in or out above a window it holds | that a place came in there, or went: the rows held move down or up one, and the list is one longer or shorter |
  | a row in inside a window, or out of one | the row at its place, or that its place went; the window then reads the row after its end, from the row there, to be whole again |
  | a row in or out after every window | that the list is one longer or shorter |
  | a row changed where it stands | the row |
  | a row whose place in the order changed | one out where it stood, one in where it stands now |
  | a row its reader may now read, or no longer | in, or out, as above |

  The list does not jump: a virtual list holds the row at the top of its view still
  ([markup.md](markup.md#long-lists)), so rows coming in above move nothing that is read.
- **A write shows at once** ([below](#a-write-shows-at-once)): a row this page adds is in
  the list in the same frame, at the place its order gives, if the window there is held
  (else the list is one longer, and the row is there when its window is); a `set` or a
  `del` of a row the page holds shows at once as anywhere; one the back end refuses is taken
  back, the count with it.
- **The line dropped** and opened again: the windows wanted are asked for again, with the
  count.
- What it costs: the first answer is the count and one window, whatever the read's length.
  For 100,000 rows of four fields that is 11 KB, against 6.1 MB for the whole read; on a line
  of 1.6 Mbit/s the first rows show in about a quarter of a second, the whole read's after
  three quarters of a minute ([bench/README.md](../bench/README.md#a-long-list-a-window-at-a-time)).

**What it does not do:**

- A `for` that is not `virtual`, or one over something made of the value
  (`orders.filter(…)`, a component's prop): it draws what the value holds, which is the
  first window and `none` for the rest, and asks for nothing more. Draw the value itself in
  a `for … virtual`. (`orders.filter(o => o != none)` is the rows held.)
- `limit`, `last`, `after`, `with` (`H330`): the windows are the list's limit, and a window
  follows no references (read the row one points at where its row is drawn). Only `find`
  has windows; a `local model` needs none (`H329`); a read that is not a `live` value's own,
  a `resource` or a `server fn`'s, is read once, whole (`H327`).
- An order not written out, or none (`H328`), and an order no index serves (`H332`): a
  window's first row is found along an index of the order, after the filter's fields
  (`index shop, placed` for `{shop: s}` by `placed`; the key has its own). A window is 10 to
  1000 rows (`H331`); a value holds 10,000 places at most.
- Where a turn's rows do not say what it did, the windows held are read again, the count
  with them, and sent whole: a filter `rowMatches` cannot answer as SQL does (one on a
  private field), a `read` rule that looks beyond the row (`exists(…)`, a reference's field)
  or into its own model, a row of another model that such a rule reads, a turn of more than
  eight rows (`addAll`, `setAll`, a cascade), a write told by `changed("Order")`, several
  apps at one database (`MOTE_SQL`), and `MOTE_ROWS=0`. That is right, and costs a count and
  a read of each window held, for each such turn and each page.
- A model with `bytes` or `file` fields: a changed row is read again by its key for what
  the page is given of it (where it stands is the write's own).
- `MOTE_ROWS_CHECK` does not check a windowed value.

Recorded: `tests/expect/real_window.txt` (100,000 rows made by the back end as it starts:
what the line carries first against the whole read; the middle and the end; a second
browser's writes above, inside and below the window in view, a row whose order changed,
rows hidden by the `read` rule, many rows in one turn; a write shown at once and one
refused; the line cut and back; each step held against the back end).

### Rules

A rule says who may do an operation **when the page asks**. (A test used in
several places can be given a name, `rule member(channel: id) = exists(Member,
{channel: channel, who: me})`, and a line then says `read if member(channel)`:
it is the same test, written once, and a `server fn`'s `requires` may name it
too. [back-end.md](back-end.md#rules).)

```text
read anyone                          everyone, signed in or not
add if me != none                    whoever is signed in
change, remove if owner == me        several operations may share a rule
write if owner == me                 `write` is add, change and remove
read if open || exists(Seat, {room: id, who: me})
read if exists(Member, {workspace: channel.workspace, who: me})
change if from == me then state in ["draft", "sent"]
change text if from == me            only these fields, for the page
change pinned, reacts if me != none  another rule, for other fields
```

- **A model with no rule for an operation is closed to the page for it.**
  `read` covers `get one find count has search searchCount`; `add` covers `add addAll`;
  `change` covers `set setAll take`; `remove` covers `del`. A page that calls a
  closed operation does not compile (`H112`); from outside there is no such
  call (404). `mote build` prints who may do what:

  ```text
  models (schema 1), and what the page may do:
    Room     read anyone · add if me != none · change, remove if owner == me
    Audit    closed to the page: only the back end's own code reaches it
  ```
  `mote check app.mote --access` prints the whole of it: each rule with who
  it admits in words, the `server fn`s and routes beside them, and what is
  worth a look ([back-end.md](back-end.md#who-may-do-what)).
- A test may use the row's fields, `me`, values written out, `== != && || !`,
  `x in [list]`, a bool field on its own, and `exists(Other, {field: value})`
  (is there a row of `Other` whose fields equal these: a field of this row,
  `me`, or a value). Nothing else (`H111`): a rule is something that becomes
  SQL and can be read.
- It may read `me.email` and the back end's settings too:
  `change if me.email in setting.list("SHOP_ADMINS")`, `read if
  setting("SHOP_MODE") == "open"`. Each is one value for the whole of a
  call, bound as a parameter like `me`; a setting is read as the back end
  starts and kept (`H163` for a `secret`): [a rule that reads a
  setting](back-end.md#a-rule-that-reads-a-setting).
- A test that is the same answer for everyone is warned of (`H162`): `change
  text if kind == "a" && kind == "b"` can never pass (it compiles, and
  closes the change to the page), `kind != "a" || kind != "b"` passes for
  anyone, `kind in []` for no one. Only what one name's equalities say;
  `mote check --access` looks further.
- **A reference may be followed one step**: where `channel` is a reference,
  `channel.workspace` is that field of the channel's row (none if the row
  is gone), wherever a field of this row may stand: `exists(Member,
  {workspace: channel.workspace, who: me})`, `channel.owner == me`. One
  step, not two (`channel.workspace.owner` is `H111`). A row need not carry
  a copy of its channel's workspace for its rule to ask about it. A kept
  value follows it: a write to the model the reference points at works the
  values on this one out again.
- **`read` is part of every query**: counts, limits, pages, `has`, `with`
  and `get` see only the rows the rule passes.
- `add if` is read against the row as it would be kept. `change if` and
  `remove if` against the row as it is; `change if a then b` also tests the
  row as it would become.
- A page changes and removes only rows it may also read.
- A reference the page gives must point at a row the page may read.

**A `change` rule may name the fields it is for**: `change text if from == me`
lets the page change `text` of a row whose author it is, and nothing else of
it. There may be several such lines, each with its own test (and its own
`then`); a `set` or `setAll` passes when **every field it gives is named by a
rule whose test holds** for that row. A rule that names none (`change if …`,
`write if …`) is for any field, and may stand beside them.

```mote
// docs: whole
model Member
  id: id = me
  name: string
  read anyone
  add if me != none

model Message
  from: Member = me
  text: string
  edited: bool = false
  pinned: bool = false
  reacts: {emoji: string, who: string[]}[] = []
  replies: int = 0
  read anyone
  add if me != none
  change text if from == me
  change pinned, reacts if me != none
  remove if from == me

// What the page cannot be trusted to say is said here.
server before Message.change(was, now)
  if now.text != was.text
    now.edited = true

server before Message.remove(was)
  if was.pinned
    fail("unpin it first")?

// A field no rule names is the back end's alone.
server fn replied(to: string): number requires signedIn
  let m = Message.get(to)?
  return Message.set(to, {replies: (m?.replies ?? 0) + 1})?.replies

state text = ""
live messages = Message.find({}, {order: "text"}) else []

action reword(id: string)
  Message.set(id, {text})?

action pin(id: string, on: bool)
  Message.set(id, {pinned: on})?

column gap=8 padding=16
  input value=text placeholder="New words"
  for m in messages key=m.id
    row gap=8
      text `${m.text}${m.edited ? " (edited)" : ""}` flex=1
      button "Reword" press=reword(m.id)
      button (m.pinned ? "Unpin" : "Pin") press=pin(m.id, !m.pinned)
  text (failure(reword) ?? failure(pin) ?? "") color=danger
```

- `Message.set(id, {replies: 9})` in the page does not compile (`H112`: no
  `change` rule names `replies`); sent from outside it is refused (400: not a
  field there). `{pinned: true, text: "x"}` from someone who is not the author
  is refused whole: `you may not change this Message`.
- Any field may be named, a list or a record (JSON) too. Not the key, a
  `hidden` field, one `= me`, or one `= now always`: those are never the
  page's to give (`H110`).
- `edited` is named by no rule, so only the hook sets it: the page cannot say
  a reworded message was never edited.
- Before there were named fields this was written `change if from == me then
  exists(Message, {id: id, pinned: pinned, …})`, pinning each field that must
  stay. That still works; a rule that names its fields says it directly.

**What a page can and cannot learn.** A row a person may not read is, to
them, a row that is not there:

| They ask | They are told |
|---|---|
| `get`, `one`, `find`, `count`, `has`, `with` | none, nothing, 0, false: as if there were no such row |
| `set` of its key | `there is no such T` (as for a key that never was) |
| `del` of its key, or by a filter | `0` |
| `add` with a unique value it already holds, or pointing at it | `you may not add this T` (the words of any refusal by a rule) |
| `find` with `after:` its key | what `after:` a key that never was gives |
| a filter or an order on a `hidden` field | what a field that is not there gives |
| a filter on a `private` field that names someone else | nothing: only one's own rows pass it |
| a `live` value it could be in | nothing: neither the row, nor its key, nor a value that says it changed |

A row they may read but not change: `you may not change this T`. A unique
value held by a row they may read: `email is taken`, of the kind `"taken"`
with `data: {model: "T", fields: ["email"]}` (a key: `there is already a T
with that id`; a `unique a, b`: `a and b is taken`). A `check`: its own
words. All of these are failures the page settles (`else`, `failure(…)`),
answered with status 422. (`taken` is the one kind among them that is not
`"said"`: a create that loses can be told from any other refusal,
[back-end.md](back-end.md#a-create-that-loses-taken).)

### Files

A field of type `file` keeps a file: its bytes in the data folder (or in an
object store: [`MOTE_FILES`](back-end.md#stored-files-in-an-object-store)),
and in the row a small record of it.

```mote
// docs: whole
model Member
  id: id = me
  name: string
  read anyone
  add if me != none

model Channel
  name: string
  private: bool = false
  owner: Member = me
  read if !private || owner == me || exists(Seat, {channel: id, who: me})
  add if me != none

model Seat
  channel: Channel cascade
  who: Member
  read anyone
  add, remove if exists(Channel, {id: channel, owner: me})

// One row a file: a message may have several.
model Attachment
  channel: Channel cascade
  from: Member = me
  file: file
  at: time = now
  read if exists(Channel, {id: channel, private: false}) || exists(Seat, {channel: channel, who: me})
  add if exists(Channel, {id: channel, private: false}) || exists(Seat, {channel: channel, who: me})
  remove if from == me

state channel = ""
live attached = Attachment.find({channel: channel}, {order: "at"}) else []

action attach
  let picked = fs.pick("image/*,video/*,application/pdf")?
  if picked
    let kept = files.upload(picked)?
    Attachment.add({channel: channel, file: kept})?

action dropped(f: {name: string, path: string, data: bytes})
  Attachment.add({channel: channel, file: files.upload(f)?})?

column gap=8 padding=16 drop=dropped
  button "Attach" press=attach disabled=pending(attach)
  if pending(attach) || pending(dropped)
    progress value=files.progress max=1
  for a in attached key=a.id
    row gap=8
      if a.file.type.startsWith("image/")
        image a.file.url width=96
      else if a.file.type.startsWith("video/")
        video src=a.file.url controls=true width=240
      a a.file.name href=`${a.file.url}?download`
      text `${Math.round(a.file.size / 1024)} KB` color=dim
  text (failure(attach) ?? failure(dropped) ?? "") color=danger
```

- **The value** is `{id, name, type, size, url}`: an id made for it, the name
  it was sent under (its last part, 200 letters at most), what kind of thing
  it is, its size in bytes, and the address it is served at. `file?` may be
  none. A `file` is a field of its own (`H110` inside a list or a record): for
  several files a row, a model of their own that points at it, as above.
- **`files.upload(picked)`** sends a file from the page (what `fs.pick`, a
  `drop=` or a `paste=` gave; a file [picked unread](data.md#files-not-read-yet)
  is sent from the disk, never whole in memory; or `files.upload(data, name)` for bytes or
  text the page made) and gives the `file` to put in a row. It waits and can
  fail. **`files.progress`** is how much of the one being sent has gone, 0
  to 1, and can stand in a binding. (A state or a variable called `files`
  hides both, as with any of the language's names.)
- **Several at once, each with its own progress**: `files.sending()`
  ([below](#several-uploads-at-once)).
- **A row takes a file once.** `T.add` and `T.set` accept only a file that
  was just sent, by the same person, and that no row has taken: a file's id
  seen in someone else's row cannot be put in a row of one's own to read it
  through that row. (`{…row}` with the file it already has is fine.) What
  the row keeps of the file is the back end's own record: the page's word
  for its name, type or size counts for nothing.
- **Its type is from the end of its name** (`.png` is `image/png`), never from
  what the page says it is; a name the table does not know is
  `application/octet-stream`.
- **It is served through the row**: `a.file.url` is
  `/file/Attachment/<the row's key>/file/<name>`, and whoever asks for it is
  asked the model's `read` rule for that row, with the cookie their browser
  sends. Someone who may not read the row is told `404 not found`, the same
  as for a row that is not there; so is someone who was let in and no longer
  is, on their very next request. An `image`, a `video`, an `audio`, a link:
  each uses the address as it is.
- **It goes when the row goes**: removed, taken by a `cascade`, or the field
  given another file or none. If the turn the row was changed in is undone
  (an `atomic` block that failed), the file stays.
- **A file sent and never taken** by a row is removed after an hour. A
  file no row of `mote_files` knows at all is kept and counted in the log,
  never removed unless the back end is told to
  ([back-end.md](back-end.md#files-no-row-knows)).
- **Sending needs someone signed in**, in a program that signs people in.
  Who may *attach* is the model's `add` and `change` rules, as for any field;
  a rule may name it (`change photo if id == me`).
- A file is **100 MB at most** (`MOTE_MAX_FILE`, in bytes, changes it). A
  larger one is refused (`a file is … bytes at most`) and nothing of it is
  kept. A file is written to disk as it arrives and read from disk as it is
  sent: the back end never holds one whole, whatever its size (400 MB up and
  down was measured at 30 MB over what the back end holds at rest). With
  the files in a store, the same: it is sent to the store 8 MB at a time
  as it arrives, and to the browser as the store sends it.

What a browser is told with a file, and why:

| Header | |
|---|---|
| `Content-Type` | From the name's end, as above. |
| `Content-Disposition` | `inline` for what a browser shows safely (png, jpeg, gif, webp, avif, bmp, video, audio, PDF, plain text), `attachment` for everything else: an `.html` or `.svg` someone sent is downloaded, not opened as a page of this site. `?download` at the end of the address makes any file a download. The file's name goes with it; `?download=<name>` gives it another ([below](#a-downloads-name)). |
| `X-Content-Type-Options: nosniff` | The browser takes the type as said, and does not guess a script out of a picture. |
| `Content-Security-Policy: default-src 'none'; sandbox` | If a file is opened as a page anyway, nothing in it runs, and it is not of this origin. (Not on a PDF: a browser's PDF viewer does not open under it.) |
| `Cache-Control: private, no-cache`, `ETag` | The browser keeps the file and asks each time whether it may still use it: a `304` if so, and never from a shared cache. |
| `Accept-Ranges: bytes` | A piece may be asked for (`Range: bytes=0-999`): `206` with `Content-Range`, `416` past the end. A film seeks without being fetched whole. |
| `Cross-Origin-Resource-Policy: same-origin` | Another site cannot embed it. |

#### Several uploads at once

`files.progress` is one number: the upload begun last. An upload that is
given a **sending** says its own, and can be stopped:

```mote
// docs: whole
model Attachment
  file: file
  read, add if me != none

shape Tray
  name: string
  up: sending

state tray: Tray[] = []

action send(f: {name: string, path: string, data: bytes})
  let up = files.sending()
  tray = [...tray, {name: f.name, up}]
  Attachment.add({file: files.upload(f, {into: up})?})?

column gap=8 padding=16 drop=send
  text "Drop files here"
  for t in tray
    row gap=8 align-items=center
      text t.name
      progress value=t.up.sent max=1
      if t.up.state == "sending"
        button "Cancel" press={t.up.cancel()}
      else
        text t.up.state color=dim
```

| | |
|---|---|
| `files.sending()` | A sending (the type `sending`): nothing is sent yet, and it does not wait. |
| `files.upload(picked, {into: up})` · `files.upload(data, name, {into: up})` | The upload as before, telling `up` how it goes. `files.progress` is left alone. |
| `up.sent` | How much has gone, 0 to 1. Followed. |
| `up.state` | `"waiting"` (not begun), `"sending"`, `"done"`, `"failed"` or `"cancelled"`. Followed. |
| `up.cancel()` | Stops it. The `files.upload` it was given to then fails with `the upload was cancelled` (for the action's `else`, or `failure(…)`), and nothing of the file is kept. Cancelled before it was given to an upload, that upload sends nothing and fails the same way. |

Each drop above runs `send` again, so every file is its own upload, begun
at once. A sending is for one upload; make another for the next.

In a `server fn`:

| Call | Gives |
|---|---|
| `files.keep(data, name)` | A `file`, from bytes or text the back end has: to put in a row. |
| `files.bytes(f)` | The bytes of a row's file, whole. |
| `files.path(f)` | Where they are on the back end's machine: for `proc.run`. (With the files in a store, they are brought there first: [back-end.md](back-end.md#stored-files-in-an-object-store).) |
| `files.derive(f, "thumb", bytes)` | Keeps a picture made from the file beside it ([below](#a-picture-kept-beside-a-file)). |

All four wait and can fail. They are the back end's alone (`H092` in the
page); `files.upload` is the page's (`H091` in a `server fn`).

#### A download's name

A file keeps the name it was sent under. A row that shows another (a
`name` field the person may change) hands the file over under that one by
saying so in the address:

```mote
a a.name href=`${a.file.url}?download=${a.name.replaceAll("%", "%25").replaceAll("#", "%23")}`
```

- The name is everything after `download=` (so an `&` or a `+` in it is
  its own), read as an address is: `%20` is a space. A `%` and a `#` in a
  name are therefore written `%25` and `%23`, as above.
- The name is anyone's to write into an address, so it is cleaned: only its
  last part (no `/`, no `\`, no leading dots), nothing that cannot be shown
  or that turns the letters around, 200 letters at most. In the header it
  goes as `filename="…"` (ASCII, with `_` for the rest and for quotes) and
  `filename*=UTF-8''…` (the whole name, encoded), as RFC 6266 and RFC 5987
  have it: nothing in it can end the header or begin another.
- **The ending stays the kept name's.** `report.html` asked for as
  `evil.exe` is saved as `evil.exe.html`; `photo.png` asked for as `x` is
  `x.png`. A file kept with no ending gets none (`run.sh` becomes
  `run_sh`). The type and whether it is shown in place come from the kept
  name, never from the address: a name cannot make an `.html` open as a
  page, and with `?download` it is a download whatever it is.
- Who gets it is still the row's `read` rule: any name, the same `404`.

#### A picture kept beside a file

A small version of a photo, the first page of a PDF, a still of a film:
the back end makes it once (with `img`, with `proc.run` and a program of
the machine's) and keeps it beside the file.

```mote
// docs: whole
// A photo with a small version of itself, and a name of the person's own to save it under.
model Member
  id: id = me
  name: string
  read anyone
  add if me != none

model Photo
  owner: Member = me
  name: string
  file: file
  read if owner == me
  add if me != none
  change name if owner == me

// A small one is made from the photo and kept beside it.
server fn small(id: string): string requires signedIn
  let me = auth.me()?
  let p = Photo.get(id)?
  if p == none || p.owner != me?.id
    return ""
  let made = img.resize(img.decode(files.bytes(p.file)?)?, 240, 0)?
  files.derive(p.file, "thumb", img.png(made)?)?
  return `${p.file.url}/thumb`

live photos = Photo.find({}) else []

action add
  let picked = fs.pick("image/*")?
  if picked != none
    let p = Photo.add({name: picked.name, file: files.upload(picked)?})?
    small(p.id)?

column gap=8 padding=16
  button "Add a photo" press=add
  for p in photos
    row gap=8
      image `${p.file.url}/thumb` width=120
      a p.name href=`${p.file.url}?download=${p.name.replaceAll("%", "%25").replaceAll("#", "%23")}`
```

- `files.derive(f, kind, bytes)`: `kind` is `"thumb"`, `"preview"` or
  `"poster"`; the bytes are a PNG, a JPEG, a WebP or a GIF (by their first
  bytes: anything else is refused), 2 MB at most. Kept again, it takes the
  last one's place.
- It is served at the file's address with `/<kind>` after it, **under the
  same `read` rule of the same row**: whoever may not read the row gets
  the same `404` as for the file, and so does a kind that was never kept.
  The type is read from the bytes again as it is served, and it goes with
  the file's own headers (`nosniff`, the sandbox, `same-origin`,
  `private, no-cache` and an `ETag`).
- It goes when the file goes (the row removed, the field given another
  file).
- A page cannot send one: what a file is shown as would then be whatever
  the person who sent it liked, and nothing could check it against the
  file. The back end makes it from the file it holds.
- Mote does not draw a PDF's pages ([pdf.md](pdf.md#showing-a-pdf) reads
  their text and pictures): a PDF's first page as a picture is made by a
  program the machine has (`proc.run(["pdftoppm", …])` on
  `files.path(f)`), and kept with `files.derive`.

- **A `server fn` that returns a row returns its file's address too**; the
  address still asks the `read` rule of whoever fetches it.
- **`bytes` in a model on the back end** (`thumb: bytes`) is the other way to
  keep bytes: in the row itself, sent with it every time it is read. Right
  for something small; a `file` for everything else. A `live` value cannot
  hold bytes (`H096`).
- **Where they are kept**: `files/` in the data folder, each under its id,
  and the table `mote_files` in `app.sqlite` (in Postgres with
  `MOTE_SQL=postgres://…`). Nothing in the data folder is
  ever served as a file of the page's, wherever that folder is. With
  `MOTE_FILES=s3://<bucket>/<folder>?endpoint=…`, the bytes are in that
  bucket instead, each under `<folder>/<id>`, and nothing of them is on
  the back end's disk ([back-end.md](back-end.md#stored-files-in-an-object-store)).

### In a server fn, and hooks

```mote
// docs: whole
model Card
  title: string
  column: string = "todo"
  owner: id = me
  read, add if me != none
  change if owner == me

model Trail
  what: string
  at: time = now

// Run around a model's writes, whoever makes them.
server before Card.add(c)
  c.title = c.title.trim()
  if c.title == "" fail("a card needs a title")?

server after Card.change(was, now)
  Trail.add({what: `${was.title}: ${was.column} to ${now.column}`})?

// The back end's own code is not checked by the rules…
server fn move(a: string, b: string, to: string): number requires signedIn
  atomic
    Card.set(a, {column: to})?
    Card.set(b, {column: to})?
  return Card.count({column: to})?

// …unless it says so: with the rules of whoever is calling.
server fn mine(): Card[] requires signedIn
  return Card.as(me).find({column: "todo"})?

state said = ""

action go
  let c = Card.add({title: "  Sand the top  "})?
  said = `${c.title}: ${move(c.id, c.id, "doing")?} doing, ${mine()?.length} of mine to do`

button "Go" press=go
text said
```

- **A `server fn` is the program's own code**: the operations run in its
  process, with no call and no rule; it sees hidden fields and may give a
  `= me` field. Guard it as any `server fn` (`requires signedIn`,
  `auth.me()`).
- **`T.as(me).find(…)`** asks as the page would for whoever made this call:
  rules applied, hidden fields left out.
- **Hooks before**: `server before T.add(row)` may change the row or `fail`.
  `server before T.change(was, now)` is given the row as it is and as it is
  about to be kept: it may change `now` (not its key) or `fail`, and the
  write is then not made. `server before T.remove(was)` may `fail`, and the
  row stays (and every row the same removal would have taken with it:
  a removal is all or nothing). A `check` and a rule's `then` are tried on
  the row as the hook left it.
- **Hooks after**: `server after T.add(row)`, `server after T.change(was,
  now)` and `server after T.remove(was)` run once the write is kept (after
  the `atomic` block it was in), and after the pages that keep a `live`
  value the write touches have been told (the order is under the table below).
  A hook that fails after the fact undoes nothing, and takes back nothing a
  page was told: it is a fault in [the log](back-end.md#logs) (`where:
  "hook"`), and [`server on failure`](back-end.md#when-something-fails)
  hears it.
- Hooks run for writes from the page and from `server fn`s alike, in the
  order written, and for rows a `cascade` takes. A `before` hook runs inside
  the write's turn: what it reads and writes of models is part of it.
- **`caller.page`** says, in any hook, whether the page asked for this write
  ([below](#who-is-writing)); `auth.me()` says who is signed in on the call.

**The order of a write** is always this. A refusal at one step means the
later ones did not happen.

| | `T.add(row)` | `T.set(key, changes)`, each row of `setAll`, `take` | `T.del(…)`, each row |
|---|---|---|---|
| 1 | what is left out gets its default; `= me`, `= now` and the key are filled | the row is found; for the page, it must be one it may read, and the rule's `change if` is asked of the row **as it is** | the row is found; for the page, one it may read and `remove if` passes |
| 2 | `before` hooks | the fields given are put in, each of its field's type; `= now always` is set | `before` hooks, then the same for each row a `cascade` takes; `restrict` refuses |
| 3 | each value is of its field's type; `check`s | `before` hooks (given the row as it was, and as it will be) | kept |
| 4 | for the page: the rule, `add if`, on the row as the hook left it | each value is of its field's type; `check`s | `after` hooks |
| 5 | each reference points at a row; `unique` | for the page: the rule's `then`, on the row as the hook left it | |
| 6 | kept | each changed reference points at a row; `unique` | |
| 7 | `after` hooks | kept, then `after` hooks | |

"Kept" is when the write's turn ends: at once for a write on its own, at the
end of the `atomic` block for one inside it. So a `before` hook can make a
row pass its rule (or fail it): what it puts in the row is what the rule is
asked about. Each step is pinned in `tests/expect/real_engine_scale.txt`.
The pages that keep a `live` value the
write touches are told as soon as it is kept, in the order writes were kept,
and before the `after` hooks run: a hook that takes its time holds no page
up. So, for one write: `before` hooks, kept, the pages told, the
[jobs](back-end.md#later-job-fn) queued in its turn free to be taken,
`after` hooks. (A job queued in an `atomic` block that is undone was never
there.)

#### Who is writing

```mote
// docs: whole
model Member
  id: id = me
  name: string
  read anyone
  add if me != none

model Upload
  owner: Member = me
  name: string
  at: time = now
  read anyone
  add if me != none

// The page's uploads are dated now, whatever the page says. The back end's
// own code may date one as it likes: a file brought in from somewhere else.
server before Upload.add(u)
  if caller.page
    u.at = Date.now()

server fn bringIn(name: string, at: number): Upload requires signedIn
  return Upload.add({name, at})?

live uploads = Upload.find({}, {order: "at desc"}) else []

action old
  bringIn("minutes.pdf", 0)?

column gap=8 padding=16
  button "Bring one in" press=old
  for u in uploads key=u.id
    text u.name
```

- **`caller.page`** is a bool, there in every hook after its rows. It is true
  when the write came through the door: the page called the model's
  operation (`Upload.add(…)` in an action, `POST /rpc/Upload.add` from
  anywhere), or a `server fn` asked as the page would (`Upload.as(me).add`).
  It is false for the back end's own code: an operation in a `server fn`,
  in `server start` or `server every`, in a route, in another hook.
- **It is the write's, not the call's.** A `server fn` the page calls that
  writes a row is the back end writing (`false`): the page could not have
  written that row itself, which is why the fn is there. What a hook writes
  while the page's write is being made is the back end's too.
- **A row a `cascade` takes** is told as the removal that took it: the page
  removes a room, and the hooks of its messages are given `caller.page` true.
- **An `after` hook** is given what its write was given, though it runs
  later (after the `atomic` block): two writes in one block, one by the
  back end and one `.as(me)`, each tell their own.
- Outside a hook there is no `caller` (`H020`); hand `caller.page` to a fn
  that needs it. A hook whose own row is called `caller` has that row.
- Before there was `caller.page` this was a hidden field the back end set
  (`sys: bool = false hidden`) for the hook to look at: a column kept for
  ever to say one thing once.
- A fn used only by `server fn`s and hooks is not in the page; a fn the page
  also uses asks as the page does when it runs there.

#### A private field

"One vote a person, and nobody told who chose what" needs the row to know
its person (for `unique poll, who`, and for `remove if who == me`) while
the page of anyone else does not. `hidden` would keep it from its own
person too. `private`, on a field that is `= me`, keeps it from everyone
but them:

```mote
// docs: whole
model Member
  id: id = me
  name: string
  read anyone
  add if me != none

model Vote
  poll: string
  choice: number
  who: Member = me private
  unique poll, who
  read anyone
  add if me != none
  change choice if who == me
  remove if who == me

state poll = "lunch"
live votes: Vote[] = Vote.find({poll}) else []

action choose(n: number)
  let mine = votes.find(v => v.who != none)
  if mine
    Vote.set(mine.id, {choice: n})?
  else
    Vote.add({poll, choice: n})?

row gap=8 padding=16
  for n in [1, 2, 3]
    button `${n}: ${votes.filter(v => v.choice == n).length}` press=choose(n)
```

For the page (the model's operations, `T.as(me)`, and the rows a
`server fn` returns):

| Asked | Given |
|---|---|
| a row that names you | the field, as it is |
| any other row | the row, with the field `none` |
| a filter on it: `{who: x}`, a list, `startsWith`, `after`, in an `any` | only your own rows can pass, whatever `x` is: so `find`, `one`, `count`, `has`, and a change or a removal by filter, cannot be made to say whose a row is. With nobody signed in, none pass |
| `{who: none}` | nothing |
| `order: "who"`, `with: ["who"]` | refused (`H064` where it is written out; `Vote is not ordered by "who"` when asked directly) |
| a `live` value | the same rows, kept the same way for each person on the line (a row sent on its own too: the field goes only to whom it names) |

So in a page, `v.who != none` reads "this one is mine". The rules still
see the field (`remove if who == me`), `unique` still holds (a second vote
is refused: it could only clash with your own), and the back end's own
code reads it whole: what it then hands a page is its business. `private`
goes on a field that is `= me` and is neither `hidden` nor the key
(`H110`).

Recorded, with every way of asking whose a vote is, in
`tests/expect/real_server_net.txt`.

#### What a server fn returns

A `server fn` reads hidden fields, and **what it returns to the page is
without them**: wherever its return type (written, or worked out) says a row
of a model stands, the hidden fields are left out at the door (and a
`private` field is `none` unless the row names who is asking). A row, a
list, a `T?`, a field of a record or of a shape, at any depth, and the
value of a `server live fn` alike.

```mote
// docs: whole
model Account
  id: id = me
  name: string
  token: string = "" hidden
  read anyone
  add if me != none

shape Board
  mine: Account?
  all: Account[]

// The fn compares tokens; the page is sent rows with no `token` in them.
server fn board(token: string): Board requires anyone
  let all = Account.find({}, {order: "name"})?
  return {mine: all.find(a => a.token == token), all}

resource b: Board = board("") else {mine: none, all: []}

for a in b.all
  text a.name
```

- It goes by the type. A row put where the type says `json`, or built into
  a record of other fields (`{name: a.name, token: a.token}`), is sent as it
  is: that is the program saying so.
- An event is not typed: `emit("joined", row)` sends the row whole. Send
  the fields meant.
- Code on the back end that calls the fn gets the rows whole; only the
  answer to the page is cut.
- `sql.run(sql.open("app")?, …)` reads and writes the same tables. A write
  made that way tells no page: say `changed("Card")` after it, and every
  `live` value on that model is worked out again.

#### A queue the page never sees

Work to be done later (mail to send, a webhook to call, a digest to build)
is rows too. **A model with no rule is the back end's alone**: no page can
read it, add to it or take from it, and from outside there is no such call.
`T.take` is what makes it a queue: it changes the first row a filter finds
and gives it, so of two callers that take at the same moment each gets a
different row, or none.

```mote
// docs: whole
model Member
  id: id = me
  name: string
  read anyone
  add if me != none

model Message
  from: Member = me
  text: string
  read anyone
  add if me != none

// No rule: only the back end's own code reaches it.
model Job
  kind: string
  payload: json
  state: string = "waiting"
  tries: int = 0
  due: time = now
  index state, due

// The message and the job it causes are kept together, or neither is.
server fn say(text: string): Message requires signedIn
  atomic
    let m = Message.as(me).add({text})?
    Job.add({kind: "mail", payload: {message: m.id}})?
    return m

// What was being done when the back end stopped is done again.
server start
  Job.setAll({state: "running"}, {state: "waiting"})?

// The job due first, if one is due: taken, done, and marked. One that fails is
// tried again later, five times.
server every 1000
  let job = Job.take({state: "waiting", due: before(Date.now())}, {state: "running"}, {order: "due"})?
  if job
    let answer = net.text(`https://mail.example/send?job=${job.id}`) else ""
    if answer == "sent"
      Job.set(job.id, {state: "done"})?
    else if job.tries < 5
      Job.set(job.id, {state: "waiting", tries: job.tries + 1, due: Date.now() + 60000 * (job.tries + 1)})?
    else
      Job.set(job.id, {state: "failed"})?

state text = ""
live messages = Message.find({}) else []

action send
  say(text)?
  text = ""

column gap=8 padding=16
  for m in messages key=m.id
    text m.text
  input value=text submit=send placeholder="Say something"
  text (failure(send) ?? "") color=danger
```

- **`T.take(filter, changes, {order})`** gives `T?`: the first row the filter
  finds (in `order`, else as added) with the changes made, or none when
  there is no such row. Nothing else is changed. It is one write, with all
  that a `set` has: the hooks, the checks, `= now always`, the `live` values
  that follow. Inside `atomic` it is part of the block (a block that fails
  has taken nothing).
- **Two callers never take the same row.** Writes take turns
  ([`atomic`](#atomic)), and a `take` finds and changes in one turn: the
  second caller's filter no longer finds what the first one changed. So the
  changes should leave the row outside the filter (`state: "waiting"` to
  `"running"`), or the next `take` finds it again.
- **The work is done outside any block.** The `take` is kept before the
  `net` call begins, so nothing waits on the mail server: neither another
  write, nor another drainer.
- **The page may `take` only from a model with a `change` rule**, and then
  as `setAll` would: a row it may read, whose `change` rule passes for the
  fields given. `Job` has no rule, so `Job.take(…)` in the page does not
  compile (`H112`).
- **Unlike a table made with `sql.run`**, a model's rows go with the rows
  they point at (`room: Room cascade`), are brought along when the schema
  changes, are typed where they are read, and are in whatever the program
  makes of its models (an export, a count). The order and the filter are a
  model's: for a queue with priorities, a field to order by.

### Models chosen at run time

A program names its models in its source, and that is what types them. Code
that is written for *any* program's models (an admin page, an export) cannot:
it learns their names as it runs. For that, and only on the back end:

```mote
// docs: whole
model Order
  title: string
  total: number = 0
  note: string = "" hidden
  by: id = me
  read if by == me
  add if me != none
  change title if by == me

rule staff = exists(Order, {by: me, title: "staff"})

// What there is to browse.
server fn tables(): string[] requires staff
  let all = models.list()?
  return all.map(m => `${m.name}: ${m.fields.map(f => `${f.name} ${f.type}`).join(", ")}`)

// A page of any model's rows, as the caller's own page would be given them.
server fn browse(model: string, after: json): json[] requires staff
  return models.of(model).as(me).find({}, {limit: 50, after})?

// The same, as the back end has them: past the rules, hidden fields and all.
server fn audit(model: string): number requires staff
  return models.of(model).count({})?

state said = ""
action look
  said = `${tables()?.join("; ")} · ${browse("Order", none)?.length} · ${audit("Order")?}`
button "Look" press=look
text said
```

| | |
|---|---|
| `models.list()` | Every model the back end keeps, in the order declared: `{name, key, fields, rules, changes, readonly, search, pointedAt}`. A field: `{name, type, kind, file, ref, optional, hidden, private, unique, filled}` (`type` as it was declared, `"time"`, `"Customer?"`; `kind`: `string` `number` `int` `bool` `json` `bytes`; `ref`: the model it points at; `filled`: `me`, `now`, `uid`, `default`, or none). `rules`: whether each of `read`, `add`, `change`, `remove` is open to a page at all. `changes`: the fields a page may change, where every `change` line names its own. `search`: the fields of its full-text index. `pointedAt`: `[{model, field}]`, the references to it. |
| `models.of(name).find(filter, options)` | An operation of the model of that name: `get` `one` `find` `count` `has` `search` `searchCount` `add` `set` `del`, as [above](#the-operations). **Past the rules**, as `T.find` in a `server fn` is: hidden and private fields are there, and nothing is asked of who is calling. |
| `models.of(name).as(me).find(…)` | **Under the rules**, as `T.as(me)` is: what the caller's own page would be given, and may change. |

All can fail, and a row is `json`: its fields are known only as the program
runs.

- **The back end's alone.** In a page `models.…` does not compile (`H160`),
  and the back end answers no call by any such name: there is nothing for a
  page to ask but the `server fn` that uses it. That fn's `requires` is the
  whole of who may, so it is never `anyone`; and what it hands back is the
  program's to choose, **since a `json` answer is sent as it is: what is
  `hidden` in a row read past the rules is taken out by nobody but the
  fn**. Prefer `.as(me)`, which leaves it out for you.
- **The name is looked up in the schema this build has, and nowhere else.**
  A name that is no model's is refused before any SQL is made (`there is
  no model …`): not a runtime table (`mote_jobs`, the accounts), not
  another app's table in a [shared
  database](back-end.md#several-apps-one-database), not a `local model`.
  Field names, filters and orders are checked by the engine as a page's
  are: a name is one the model has, a value is bound and never written into
  the statement.
- **Every write is a write of the engine's**: defaults, `before` hooks,
  types and `check`s, references, `unique`, `after` hooks, `live` values,
  and inside [`atomic`](#atomic) the block's own turn.
  [Looking only](back-end.md#acting-as-someone) refuses it; a `readonly`
  model refuses it.
- [`mote check --access`](back-end.md#who-may-do-what) cannot say which
  model such a fn reaches, and says that: `reads any model, chosen as it
  runs (models.of), with no rule asked`.
- The [admin extension](admin.md) is written on this; so is nothing else
  in Mote.

## Full-text search

`index text, title fulltext` in a model keeps an index of the words in those
fields; `T.search(words, filter, options)` gives the rows that hold the words,
each with a `rank` and a `snippet`, and `T.searchCount(words, filter)` says how
many there are. Both are reads: under the `read` rule like `find`, in the same
query.

```mote
// docs: whole
model Member
  id: id = me
  name: string
  read anyone
  add if me != none

model Channel
  name: string
  private: bool = false
  owner: Member = me
  read if !private || owner == me || exists(Seat, {channel: id, who: me})
  add if me != none

model Seat
  channel: Channel cascade
  who: Member
  unique channel, who
  read if who == me
  add if exists(Channel, {id: channel, owner: me})

model Message
  channel: Channel cascade
  from: Member = me
  text: string
  at: time = now
  index channel, at
  index text fulltext
  read if exists(Channel, {id: channel, private: false}) || exists(Seat, {channel: channel, who: me})
  add if exists(Channel, {id: channel, private: false}) || exists(Seat, {channel: channel, who: me})

state words = ""
state newest = false
// (Put around each hit in a snippet: something no message holds.)
fn lit(): string = "\u0001"

live found = Message.searchCount(words) else 0
live hits = Message.search(words, {}, {order: newest ? "at desc" : "rank", limit: 20, snippet: {mark: lit(), around: 16}}) else []

column gap=8 padding=16
  row gap=8
    input value=words placeholder="Search messages" flex=1
    button (newest ? "Newest first" : "Best first") press={newest = !newest}
  text `${found} found` color=dim
  for h in hits key=h.id
    text
      for piece, i in h.snippet.split(lit()) key=i
        if i % 2 == 1
          mark piece
        else
          text piece
```

Someone who is not in a private channel finds none of its messages, is not
told how many there are, and is shown no word of them: not because the
results are filtered afterwards, but because the rule is part of the
question.

- **The declaration.** One `index … fulltext` line a model, naming `string`
  (or `string?`) fields. **Not a `hidden` field, not a `private` one, not the
  key** (`H110`): the index holds only what every reader of the row may
  read, so neither a match nor a snippet can give away anything else. To
  search what is hidden, a `server fn` with `sql.run`.
- **Kept current by SQLite itself**, for every write to the table: `add`,
  `set`, `del`, the rows a `cascade` takes, an `atomic` block (undone with
  it), and a write made around the model with `sql.run`. Nothing is rebuilt
  when a row is added. (The index is the FTS5 table `T_fts`, fed by three
  triggers on `T`; leave both alone. `insert or replace` by `sql.run` goes
  past a delete trigger, as SQLite has it: write `update`.)
- **On both sides**: a `local model` is searched in the page's own SQLite
  (which has FTS5), with no rules, and a `resource` over a search follows the
  page's writes like one over a `find`.
- **Words** are runs of letters and digits; case and accents do not count
  (`resume` finds `Résumé`). No stemming (`fox` does not find `foxes`:
  `fox*` does), no list of ignored words. A run of letters with no spaces
  in it (Chinese, Japanese) is one word.

**What is typed.** `words` is a person's text, and is read as this and
nothing else:

| Typed | Finds rows that |
|---|---|
| `quick fox` | hold both words, anywhere in the indexed fields |
| `"quick brown"` | hold the words next to each other, in that order |
| `-dog` · `-"lazy dog"` | do not hold the word, or the phrase |
| `fox*` | hold a word that begins so (two letters at least before the `*`) |
| `well-known`, `a.b@c.test` | hold those words next to each other (what is not a letter or a digit only separates) |
| `AND` `OR` `NOT` `NEAR(a b)` `text: x` `^a` `(a)` | hold those as words: the index's own syntax is never the caller's |

What is typed is read and written out again for the index, each term between
quotes; none of it is passed through. A term with no letter or digit in it is
left out; a search with nothing left to find (`""`, `-fox` alone) gives `[]`
and `0`, and is not a failure. A quote that is never closed takes the rest.

**The options** of `search`:

| Option | |
|---|---|
| `order: "rank"` | The default: best first, and of equals the newest (the one added last). |
| `order: "at desc"` | By a field, as in `find`. |
| `limit: 20` | 50 when not said. |
| `after: row` or `after: key` | The rows after that one in the order, as in `find`: the next page. |
| `snippet: {field: "text", around: 12, mark: "*"}` | What `snippet` is: about `around` words (1 to 64, 12 when not said) of `field` (one of the indexed fields; the first when not said) around the best hits, with `…` where it is cut. `mark` is put before and after each hit: `r.snippet.split(mark)` gives pieces of which **every second one is a hit**. With no `mark` the snippet is plain text. |

What comes back is `T`'s rows, each with two fields more: `{…, rank: number,
snippet: string}` (so a model with an index has no field called `rank` or
`snippet`: `H110`). A snippet is text, never markup: show it with `text`.

**`rank`** says how well one row matches: with *h* the number of hits in the
row's indexed fields (a phrase is one hit) and *l* their length in letters,

```text
rank = h / (h + 1 + l / 100)        between 0 and 1; more hits is more, a longer text is less
```

It is worked out from the row and the words alone, on purpose. The usual
measure (BM25, which FTS5 offers and the [`search`](text.md#search) battery
uses) also weighs each word by how many rows hold it, and those rows include
the ones a person may not read: their rank values, and the order of their own
rows, would then shift as rows they cannot see come and go. Here a row's rank
is the same whoever asks and whatever else is kept, so there is nothing to
learn from it. The back end's own code is given the same rank.

**The caps**, for the page (each a failure it settles, 422):

| | |
|---|---|
| the search | 500 letters, 16 terms (a phrase is one); `a search is 500 letters at most` |
| a prefix | two letters before the `*`; `a word that ends in * needs two letters before it` |
| `limit` | 200; `T.search gives the page 200 rows at most at a time: ask for the rest with `after`` |
| `snippet.around` · `snippet.mark` | 1 to 64 words · 32 letters |

The back end's own code may ask for any `limit`, and for 4000 letters and 64
terms.

**What a page can and cannot learn.** As for `find`
([above](#rules)), a row a person may not read is a row that is not there:

| They ask | They are told |
|---|---|
| `search`, `searchCount` for words only such rows hold | `[]`, `0` |
| `limit`, `after` | pages of their own rows; rows they may not read take no place in them |
| `after:` the key of such a row | what `after:` a key that never was gives (`[]`) |
| a filter that names such a row (`{id: its key}`, its channel) | nothing |
| `rank`, and the order of their rows | the same before and after any number of rows they may not read are added |
| `snippet: {field: "secret"}`, an `order` or a filter on a `hidden` field | what a field that is not there gives |
| a filter on a `private` field | only their own rows pass, as in `find` |
| `/rpc/T.search` on a model with no `read` rule, or no index | 404: there is no such call |
| a `live` search | a value only when theirs differs |

Not hidden: how long an answer takes, which grows with the rows the words
find before the rule is asked (as a `find`'s does with the rows its filter
finds).

- **In a `server fn`** a search has no rules and sees every row; with
  `T.as(me).search(…)` it is the page's. Rows it returns to the page go
  without their hidden fields, as a `find`'s do.
- **`live x = T.search(…)`** is kept current like a `find`: worked out again
  when a row that passes its *filter* is written (whatever words it holds),
  or a model its `read` rule looks into.
- **What it costs.** By a field (`order: "at desc"`), a search costs about
  what the `find` with that filter and rule costs; snippets are cut only for
  the rows given. By `rank`, every row the words find is ranked before the
  best are taken. Measured on 100,000 rows of which half were in a channel
  the asker was not in, with a word every row holds: counted in 35 ms, a page
  of 50 by a field in 38 ms, by rank in 91 ms (144 ms for someone who may read
  them all); a word few rows hold, 2 ms.
- **Adding the index to a model that has rows** is a step of
  [`schema.lock`](#changing-a-schema) like any other: the index is built
  from the rows there. Changing its fields, renaming one of them or the
  model, builds it again; taking the line away drops it (no data goes with
  it, so nothing is asked).

Recorded, with everything someone hostile was told, in
`tests/expect/real_fulltext_server.txt`.

## Changing a schema

(Several apps that keep their models in one database, `MOTE_SQL`: each
program still has its own `schema.lock`, and what a start-up does there is
in [back-end.md](back-end.md#starting-up-whose-schema).)

The source is the schema. `mote build` (and `mote dev`) writes what it made
of the models to **`schema.lock`** beside the entry: keep it with the
source. It holds the tables as the last build knew them and every step
(SQL) that led there, numbered; each database remembers the number it is at.

- The back end brings its database up to the build's schema **when it
  starts**; a page does so **when it first uses a local model**, in one
  transaction. A new database gets the whole schema at once.
- **What the data can follow by itself is done for you**: a new model; a new
  field with a default or `?`; an index, `unique`; a full-text index (built
  from the rows there); a rule, a check, a default (no step at all); a
  field that may now be none.
- **A rename is `was`**: `subject: string was title`, `model Topic was
  Thread`. The word may stay.
- **What could lose data is refused** by `mote check`, `build` and `dev`
  (`H115`), with the way through:

  | Change | The way through |
  |---|---|
  | a field or a model removed | `mote migrate --drop T.field` (or `--drop T`); or, in the source, the line `dropped field` in the model, `dropped T` at the top |
  | a new field that must be there, with no default | give it a default, or `?` |
  | a field that could be none and now must be there | give it a default (the rows with none get it), or keep the `?` |
  | a changed type, a changed key | add a field beside it, fill it in a [`migrate`](#a-change-to-the-data-itself-migrate) block, drop the old one |

- `mote migrate app.mote --plan` prints the SQL the last changes ask of a
  database and writes nothing; `mote migrate app.mote` writes the lock, as a
  build would ([cli.md](cli.md#mote-migrate)).
- **A build older than the data it finds** (one deployed again after a
  newer one, a rollback, a page left open in a tab) uses it as it is when
  every step since its own only added: a new model, a new field with a
  default or `?`, a plain index, a full-text index. It reads and writes
  what it knows; what it adds is given the newer fields' defaults (or
  none), and the data stays at the newer schema. Otherwise (a rename, a
  drop, a field filled in for the rows there, a `unique` index since) it
  refuses: the back end stops with why (`the data is of a newer schema
  than this build knows, and a step since changed what was there`); a
  page's operations fail with `this page is older than the data it keeps
  here: reload it`. (Each database keeps, beside its version, the oldest
  version that may use it, `reads`, written by the build that brought it
  there: the plan in the built code says it, `{version, reads, …}`. A
  database a build from before this rule brought up has none, and is
  refused as before until a newer build starts on it.)

### A change to the data itself: migrate

The schema's steps change the shape of the tables. What the rows already
there should hold is the program's to say, once:

```mote
// docs: whole
model Entry
  what: string
  // As it was typed, in the first build; and what it comes to, in this one.
  amount: string
  cents: int = 0
  read anyone
  add if true

// Run once for a database, when the back end starts on it: the rows that
// were there are given their cents.
migrate "amounts as cents"
  for e in Entry.find({cents: 0})?
    Entry.set(e.id, {cents: Math.round(Number(e.amount) * 100)})?

// Raw SQL, for what is quicker said so.
migrate "what, tidied"
  sql.run(sql.open("app")?, "update Entry set what = trim(what)")?

live entries = Entry.find({}, {order: "what"}) else []

for e in entries key=e.id
  text `${e.what}: ${e.cents / 100}`
```

- **`migrate "name"`** + a block of the back end's own statements (the
  models' operations, past their rules, and `sql.run`). It is run **when the
  back end starts**, after the database has been brought to this build's
  schema and before anything else: before `server start`, before the first
  call is answered (`/readyz` waits for it).
- **Once for a database, by its name.** What has run is written down in the
  database (`mote_migrated`), in the same turn as the block's own writes. So
  a name is never changed once a build with it has been started, and a
  block that has run everywhere may be taken out of the source. Two of one
  name are refused (`H145`).
- **In the order written, each in a turn of its own**: all of a block is
  kept, or none of it. One that fails stops the back end as it starts, with
  why (`` mote: `migrate "amounts as cents"` failed, and nothing of it was
  kept: … ``); the database is as it was before that block, and the blocks
  before it stay done.
- **It waits on nothing but the data**: a request, a program or `detach` in
  one is refused (`H145`), since the whole block holds the write turn while
  the back end is starting. Fetch what it needs in a `server start` block
  that keeps it in a row; do what follows in a
  [`job fn`](back-end.md#later-job-fn) queued in the block.
- Nobody is signed in in it; hooks run for what it writes, as for any write
  of the back end's own code.
- **With several back ends at one database**
  ([`MOTE_SQL`](back-end.md#several-apps-one-database)), one of those that
  start runs each block, under the lease the schema's steps are done under;
  the rest find it done. A name is the database's, whichever program
  declares it: a `migrate` in a package two apps use runs once.
- A new database runs them too, on no rows: write each so that it is right
  there (a `find` that finds nothing).

(Run, with a build that fails half way, by `tests/all.sh real_migrate_blocks`.)

## For agents

The `mote-agent` block, `agent.json` and `llms.txt` list each model: where
it is kept, its fields (not the hidden ones), and each operation the page
may ask for with what it takes, what it gives and who may. In `agents.mote`,
`model Message "What was said in a room."` says what one is for, and `model
Audit hidden` leaves one out ([agents.md](agents.md)).

## Refused

| You write | Message |
|---|---|
| a model's line that is wrong (two keys, a default of the wrong type, `always` without `= now`, `cascade` on a field that is no reference, a rule on a `local model`, a `file` in a `local model` or inside a list, …) | `H110`, with what to write |
| in a rule, something that cannot become SQL (`n > 3`, a call, a field that is not there) | `H111` |
| from the page: an operation with no rule, a `hidden` field, a `= me` field given, a change to a field no `change` rule names | `H112` |
| a `local model` in a `server fn` or with a hook; `T.as(me)` in the page; `live` on a `local model` | `H113` |
| `atomic` in the page around a model on the back end, or around a call to a fn that waits | `H114` |
| a change to the models that could lose data | `H115`, with the way through |
| a write of, or a hook on, a model the program says it only reads (`readonly Price`) | `H118`: write it in the app that owns it ([several apps, one database](back-end.md#readonly-a-model-an-app-only-reads)) |
| `Note.find({titel: "x"})`, `Note.findAll()` | `H063`: no such field (did you mean `title`?), no such operation |
| `caller.page` outside a model's hook | `H020`: unknown name `caller`, with where there is one |
| `Job.take(f, changes, {limit: 2})` | `H064`: `take` has `order`, and takes one row |
| `Note.find({rank: "high"})`, `Note.add({body: "x"})` | `H067`: `rank` is number, not string · `Note.add` needs `title` |
| `{order: "rnk"}`, `{done: after(1)}`, `after(3)` outside a filter, an `any` that is not a list of filters written out | `H064` |
| `index secret fulltext` on a `hidden` or `private` field, the key, or what is not a `string`; a second `index … fulltext`; `T.search` on a model with no such line | `H110` |
| `T.search(q, {}, {snippet: {field: "at"}})` (not in the index), `{with: […]}`, `{last: 3}` · `{snippet: {around: 99}}` | `H063` · `H064` |

## Pitfalls

- **A filter is exact.** `{name: startsWith("a")}` does not find "Apple".
  Keep a lower-case copy of the field if you need that.
- **"Find it or make it" is [`T.put(row)`](#put-and-inc)**, by the key or a
  `unique` set, in one turn. `T.one(f)? ?? T.add(row)?` is two, and two
  pages doing it at once can both add.
- **A reference `= me` needs the person's row.** `from: Member = me` fails
  with `there is no such Member for Message.from` until that person has a
  `Member`. Add it when they sign up.
- **Rules are for the page; a `server fn` is trusted.** Putting a write in a
  `server fn` takes it out from under the rules unless it says `.as(me)`.
- **A write the back end refuses does not undo the rest of its action.**
  The row is taken back; the field the action cleared after it stays
  cleared, and the place it went to stays gone to. Put what must be put
  back in the write's `else`, or say `confirmed` at that call
  ([a write shows at once](#a-write-shows-at-once)).
- **`disabled=pending(save)` no longer holds a button down** while a row is
  on its way, where `save` only writes a model: the action is over at once.
  Dim the row with `pending(row)`; or say `confirmed`, and the action waits.
- **What a `server before` hook changes in a row shows when the answer
  arrives**, not before: a name it trims shows untrimmed for that moment.
  An action that reads the row it added waits for the hook by itself.
- **`change if …` with no fields lets the page change every field** it can
  give, the reference to its room and a counter the back end keeps included.
  Name the fields.
- **A `read` rule with `exists` is a sub-query per row.** Index what it
  matches on (`unique room, who` does).
- **A write to a model that another's `read` rule looks into works every
  `live` value on that other model out again**, on every open line: unless
  the rule only ever asks for the caller's own rows of it (`exists(Seat,
  {room: room, who: me})`, in every `exists` on that model). Then a `Seat`
  written for one person works out only that person's values. Write
  membership tests that way: with `me` pinned to a field.
- **`with` follows one step**, and gives none for a row the page may not
  read. A rule follows one step too (`channel.workspace`): each use is a
  look-up by key for every row the rule is asked of.
- **A search is not a filter with a twist.** `{text: startsWith("fox")}` is
  an exact test of the whole field; `T.search("fox*")` looks for a word
  anywhere in it. Narrow a search with its filter (`T.search(words,
  {channel: id})`), which is tested in the same query.
- **`VACUUM` (run by hand, with `sql.run`) may number a table's rows anew**,
  and a full-text index knows its rows by that number: after one, build the
  index again (`insert into Message_fts(Message_fts) values('rebuild')`).
  Mote itself never runs it.
- **A `live` search over a busy model is worked out again on every write
  its filter passes**, whatever the words: give it a filter (one channel),
  or make it a `resource` that runs when the words change.
- **Under `mote dev` every saved change to a model is a step in
  `schema.lock`.** Before the first release, delete the lock and the data
  folder (`.data`, or the site's data in the browser) to start clean.
- **Two models cannot have the same name as a shape**, and a model's field
  cannot be called `me`.
- **On the back end, a block that waits holds every other write.** `atomic`
  around a `net` call keeps each write behind it waiting for that answer
  (reads go on). Keep what must be one in the block and do the slow part
  before or after: write the row that says "to do" in the block, and do it
  outside ([a queue](#a-queue-the-page-never-sees)).
- **`sql.run` on `sql.open("app")` is on the connection the writes use.** It
  does not take a turn: run while a block is open, it is in that block (it
  sees the block's writes, and is undone with it if the block fails).
- **Two reads outside `atomic` are two moments**: a row counted by the first
  may be gone by the second. One `find` with `with` is one moment.
- **A file's address is the row's**: give a row another file and the same
  address serves the new one. The `ETag` is the file's id, so a browser that
  kept the old one is sent the new.
- **A page's `atomic` holds the page's database** until it ends: do not wait
  for the network inside one.

## In the source

| What | Where |
|---|---|
| The declaration, hooks, `atomic` | `compiler/src/parse.rs`: `Parser::model`, `body`, `stmt`; `ast.rs`: `Model`, `Stmt::Atomic` |
| What a declaration means, rules to data, the tables, `schema.lock`, the plan | `compiler/src/model.rs`: `read`, `rule`, `data`, `create`, `plan`, `Lock` |
| The operations' types, filters, rows, options | `compiler/src/types.rs`: `Checker::model_call`, `model_filter`, `model_row`, `model_options`, `models` |
| The calls written out: the engine, or a call to the back end | `compiler/src/emit.rs`: `Gen::model_call`, `model_checks`, `Stmt::Atomic` |
| A write shown at once, `confirmed`, `pending(row)` | `compiler/src/emit.rs`: `at_once`, `shows_at_once`, the `Else` beside a write; `parse.rs` (`confirmed` before a call, and as a model's line); `model.rs`: `page_data`; `types.rs` (`H126`); `build.rs` (`MWS`, `writes=`); `runtime/page/writes.mote`: part `MW`; `runtime/page/rpc.mote`: `LVR`, `RPC`; `runtime/page/actions.mote`: `PD` ([internals.md](internals.md#a-write-shown-at-once)) |
| The schema in the page and in `server/main.js`; the lock read and kept | `compiler/src/build.rs`: `finish`, `keep_lock` |
| The engine: an operation to SQL, rules, checks, turns | `runtime/shared/model.mote`: parts `MD`, `MDM`, `MDK` |
| The page's side: its SQLite, resources that follow, the other windows | `runtime/page/model.mote`: part `MX` (`modelDone`, `modelHear`); `runtime/page/storage.mote`: part `SQ` (`take`, `rest`, `begin`, `end`) |
| The back end's side: who is asking, hooks, `live` values, the door | `runtime/server/model.mote`: parts `MX`, `MDD`; `runtime/server/serve.mote`: `VAL` (`x`, `f`, `e`) |
| A kept read brought up to date by rows | `runtime/server/model.mote`: `modelTell`, `rowsPlan`, `rowFor`, `rowsSend`; `runtime/page/rpc.mote`: part `LVR` (`rowsApply`); `runtime/shared/model.mote`: `MDM` (`rowMatches`, `valueOrder`) |
| Reads beside a block: the reading connection, one snapshot a read | `runtime/server/model.mote`: `modelOpen` (the pragmas), `modelApart`, `modelRun`; `runtime/shared/model.mote`: `modelOp`, `act` (`env.aside`) |
| `T.take` | `runtime/shared/model.mote`: `act`, `rowsFor`; `compiler/src/types.rs`: `Checker::model_call` |
| `caller.page` | `compiler/src/parse.rs` (a hook's last parameter); `runtime/shared/model.mote`: `addRow`, `changeRow`, `removeRow` (`page` on each change); `runtime/server/model.mote`: `modelDone` |
| A model with a component's name, on the back end | `compiler/src/emit.rs`: `find_server`, `Gen::model_recv` |
| Rules that name fields | `compiler/src/model.rs`: `read` (`changes`); `runtime/shared/model.mote`: `changeSql` |
| Files: kept, taken by a row, served, swept | `runtime/server/files.mote`: part `FILE`; `runtime/page/rpc.mote`: part `FUP`; `runtime/shared/model.mote`: `withUrls`, `addRow`, `changeRow`, `removeRow` |
| Hidden fields left out of what a `server fn` returns | `compiler/src/types.rs`: `hide_plan`; `runtime/server/serve.mote`: `shown` (`SHW`) |
| Full-text search | `compiler/src/model.rs`: `read` (`fulltext`), `fulltext_sql`, `plan`; `compiler/src/types.rs`: `Checker::model_call`, `search_options`, `hiding`; `runtime/shared/model.mote`: part `MDQ` (what is typed, made into what the index is asked), `searched`, `searchCounted`, `searchRank`, `searchFrom`; `runtime/server/model.mote`: `modelDoor` |
| A `private` field | `compiler/src/model.rs`: `read`, `table` (`priv`); `runtime/shared/model.mote`: `fromRow`, `shownRow`, `filterSql`, `orderOf`, `follow`; `runtime/server/serve.mote`: `shown` (`?name`) |
| `mote migrate` | `compiler/src/main.rs` |
| Recorded behaviour | `tests/models`, `tests/tabs` (two windows at once), `tests/models_server`, `tests/backend3` (with `tests/backend3.real.mjs`: what someone hostile is told), `tests/engine_scale` (with `tests/engine_scale.real.mjs`: several callers at once), `tests/fulltext_server` (search, with `tests/fulltext_server.real.mjs`), `examples/slick`; `compiler/src/tests_model.rs`, `tests_engine_more.rs`, `tests_fulltext.rs` |
