Remote / foldkit-remote

Mutations and optimistic state

Register mutations on the domain:

ts
import { Mutation } from 'foldkit-remote'

const RenameProject = Mutation.make('RenameProject', {
  Input: { id: Schema.String, name: Schema.String },
  Output: { id: Schema.String },
})

A mutation starts from ordinary application update:

ts
case 'ClickedRename': {
  const { id, name } = message

  const { model: started, command } = Data.mutate(
    model,
    RenameProject,
    { id, name },
    {
      optimistic: [Remote.patch(Project, id, { name })],
    },
  )

  return { model: started, commands: [command] }
}

Data.mutate does two things:

  1. it applies MutationStarted to the Model, including any optimistic overlays;
  2. it returns the Command that calls RemoteClient and eventually emits MutationSucceeded or MutationFailed.

Remote.patch(entity, id, values) builds one entity's patch, and Remote.ref(entity, id) names one row. Both take the entity you declared, whether with foldkit-entity or Remote's Entity.make, and check values against its fields in their wire shape, except a relation, which is a ref: owner: Remote.ref(User, 'u1'), an array of refs for a many, or null where it is optional. The patch holds the ref key the store keeps. A ref key typed by hand ('User:u1') or a ref to another entity is refused, by the type and when the patch is made.

Those settlement Messages go through Data.reduce like every other Remote fact. The request id comes from the Remote Model's sequence, so update stays pure. Settling is idempotent per requestId.

Answers settle in the order their requests started, not the order they arrive. The server applied the requests in that order, so an answer does not overwrite a field, or clear a row's deletion, that a request started after it has already settled; and an answer's deleted does not delete a row a later request has written. Two renames answered out of order keep the second name, and an edit answered after the row's delete leaves it deleted. Reads and live patches are the server's word at the time they arrive and land as they come. The ledger keeps each pending request's place in mutations.order, and the place of the last answer to write each field in mutations.settled, only while an earlier request is still pending.

A mutation that deletes says so. The server's outcome carries deleted: [{ entity, id }], and settling it tombstones those entities: they read NotFound, and they leave every connection and relation they were in, so the server names no list. Patches apply first, so an entity named both ways is deleted; a retry of the same request deletes nothing again.

A delete can show before the answer, with no list named either. Remote.tombstone(entity, id) in optimistic is a pending tombstone: while the request is in flight the row reads NotFound and leaves every list and every relation that lists it, as a settled delete does. It is a layer like a patch, so the server's store is untouched (Data.confirmed still reads the row), a failure brings the row back everywhere, and the answer's deleted keeps it gone. A pending delete wins over every pending patch of its row. A declared Write.delete shows this without being asked, and with it every row the store holds that is declared to go with the row (Relation.one(Post, { onDelete: 'cascade' }): its replies, theirs, the likes of each), each moving the counts over it; the answer names them deleted. A delete of a row something restricts ({ onDelete: 'restrict' }) is shown as pending too, since the client may not hold the rows pointing there; the server refuses it as Refusal.referenced, and the row comes back. A row the store holds whose link the delete clears ({ optional: true, onDelete: 'setNull' }) is shown pointing nowhere, and leaves the lists filtered on it; a held row whose may refuses that unlink refuses the delete where it is made, in the server's words.

ts
Data.mutate(model, DeletePost, { id }, { optimistic: [Remote.tombstone(Post, id)] })

A pending patch shows a field before the server has sent it, but does not stand in for it: a read still fetches a field of a row the server holds that only a layer shows, so a failure that takes the layer away leaves the server's value, not Initial. A row only a request holds (one the store has never read, or read as absent: a pending create) is not fetched while the request is pending, since the server has nothing of it yet; once the answer lands, the fields it did not carry (a guard's may) are.

Optimistic entity patches are layers over the base store, not inverse patches. If multiple mutations overlap, the visible cache is recomputed as base plus the still-pending layers, so settling one does not require trying to undo its old value manually.

Connections can be optimistic too:

ts
import { ConnectionChange } from 'foldkit-remote'

const { model: started, command } = Data.mutate(model, AddComment, input, {
  optimistic: ({ tempId }) => [
    Remote.patch(Comment, tempId, { id: tempId, body: input.body }),
    ConnectionChange.prepend(
      CommentsForPost.ref({ postId }),
      Remote.ref(Comment, tempId),
    ),
  ],
})

A successful server result can replace the request's temporary connection overlays with confirmed ones in place.

Which lists a write moves

Which lists a mutation changed is worked out from its answer. Each patch says which row it wrote; the fields whose value differs from what the client held are what changed (an answer returning a whole row changes only what is new). Every loaded list over that Entity is judged by its query's body against the store the answer left:

  • a list whose body reads none of the changed fields stands;
  • a row it holds that still matches, or a row it does not hold that still does not, leaves it standing;
  • a held row that stops matching leaves it, with nothing fetched: whether a row belongs is the body's, judged exactly;
  • a row that starts matching, a row new to the client, a held row whose ordering field changed, or a row whose order moves it in from past what a list has loaded, is placed where the body's order puts it among the rows loaded (placeIn), when the order is placeable (Query.placement); a row that sorts past what is loaded is left out of it (and out of what showed it), for the next page. A row that was itself where a page met rows not loaded (the last before a cursor, the first after one) cannot be told to have moved past it, its old values being gone, so it invalidates the list instead;
  • anything else invalidates it, and its read entry fetches it again: a row the client cannot judge (it lacks a field the body reads), an order it cannot place (text with no declared collation, the server's own), or a row an optimistic overlay shows; a read of it already in flight is restarted, since it could answer with the rows before the write;
  • a list over a Query.make query, which declares no body, is invalidated by any change, of any Entity: its server may read another Entity's rows too;
  • a list whose body reads other rows (a path, an exists, a path from the viewer) is judged again over the store, and fetched, by a change to any member those read, or a row of theirs made or deleted: a team renamed moves every member listed by its name, and a follow brings the followed account's posts into a feed over Expr.exists. A row the body no longer admits leaves, and a row the store holds that it now admits joins where the order puts it, so the list shows that until its page arrives (in the answer itself, when the write sent for it). A row of the list's own the change moves by the order goes where the order puts it. An exists is true over the store where a row the store holds points here and passes its filter. It is false only where the store holds every row the filter may count: a list it holds whole (read to both ends, not stale) whose body only fixes fields to values (Expr.eq(Follow.relations.follower, input.accountId)) that the exists' filter fixes too, every row of which the store holds with the link the exists reads. So with the viewer's whole Following held, an unfollow takes the unfollowed account's posts out of a feed at once; without it the exists is not known, and they wait for the feed's page. A change to the link a path starts from re-judges that row alone;
  • a row a list does not hold that changes a member the server's own read rule filters on (an owner, a team: declared on the Entity as ReadFilter, which foldkit-guard attaches) invalidates it: whether the row now belongs is the server's to say, since the client runs no such rule. A row it holds is judged by the body as usual. A new row counts, so under such a rule a create refetches the lists over its Entity;
  • a list whose body declares no order leaves its order to the server, by fields the client cannot see, so any change to a row it holds invalidates it. Declare the order in the body (Query.orderBy) to keep a list that a change provably did not move.

The client runs a body's primitive operators by its own table. Remote.make({ ..., operators }) (Operators.kernel by default) is the table it matches, filters and places rows with. A body calling an operator the table does not run is judged by the server, as any row the client cannot judge is: filtered answers it incomplete and a change to it refetches. The domain carries only the table it was given (Data.operators, an Option, none for the default): what judges a body on the client takes the kernel's for none, so a page that only reads keeps none of Entity's expression code.

A pending custom-operation write replays only where you give its implementation. A write that combines a field with a custom operation (combines in a pending patch) is replayed over a newer value when its answer lands, instead of the field being read again, only if Remote.make({ ..., replay: { foreign, rewritePolicy } }) holds the page's implementations of the operation and a policy that applies its commutative and associative claims (Expr.RewritePolicy.verified(evidence) or trusted). Without either, the field is read again.

A placement can be checked against the server. Remote.make({ ..., verifyPredictions: true }) places as usual, and also fetches each list it placed what the server said in (an answer, as above, or a read or a live patch, as below); when the server's first page arrives it is compared with the order placed, and a disagreement is a PredictionMismatch diagnostic whose part is a Placement: an order the page does not share, or a row placing took out that the page still lists. A pending edit is not checked: the server does not have it yet. Turn it on in development and tests: a collation the client and the server disagree on then fails an assertion instead of misplacing a row for a reader.

So a rename updates every view of the row and fetches nothing, a status change moves a row out of the lists filtered by status and into the others in their order, and a price change moves the row within a list sorted by price, all without a request.

A list the write moves comes back with its answer. The judgement above runs twice: when Data.mutate sends the write, against what its optimistic change predicts, and again on the answer. Each list an active Surface reads that the prediction leaves to be fetched, or leaves short of its window (a row archived out of a full page, whose read entry would ask for the next row), is sent with the request as the first page its read entry would ask for (the query, its input, first and select). The server reads each after the write, as a query of it is read, and answers it beside the rows. In the reduction that releases the layer, each list the answer moved takes its page in place of the fetch, so it reads Ready throughout without an extra round trip.

A page lands only in a list the answer itself moved, and not in one stale before the write, whose own read is on its way. Everything else falls back to the fetch above: a write that predicts nothing, a list read from a cursor or from its end, a list the server does not answer (past maxIdsPerEntity across the request's lists, more than MAX_ANSWER_LISTS, or a read that failed), and a page longer than its window. Under verifyPredictions a placed list is checked against its carried page, so the check asks nothing either.

A pending edit, and the server's word on a row, are placed the same way. While a request's optimistic patch or an overlay is pending, a list that holds the row shows it where the edit puts it, or leaves it out once it stops matching; the server's pages are untouched, and lifting the edit puts the row back. A read or a live EntityPatched that brings a new value for a row a list holds moves it in the list's pages, as an answer does. Neither brings a row into a list, since what the list selects of it may not be loaded, and neither fetches: a list it cannot place stands as it is. The exception is a pending write to what a body reads through other rows (a follow under a feed of the accounts one follows): the list is judged again over the store and the layers, and shows the rows the store holds that the body now admits, and none it no longer does, until the write settles; an exists is decided over the lists held whole, as an answer's is.

An inserted row is drawn in order. A ConnectionChange.prepend or append (a pending create's, a confirmed one's) and a live ConnectionInsert say a row is in a list; they do not say where. In a list the client can place, a read draws the row where the body's order puts it, or leaves it out when it sorts past what is loaded; one it cannot place (a field the order reads is missing, the order is the server's) stays at the end its change names. Data.visibleItems(remote, connection) gives a list's edges as its reads draw them, for a persistence snapshot that stores a list as shown. Data.refresh stays for what an answer cannot say, such as a server-side effect on rows it did not return.

Which lists a declared write can reach

The judgement above runs on an answer. The same question can be asked before anything is sent, of the declarations alone: reaches(write, query) compares what a write may write (Write.writes) with what the query's body reads (its fields, and what it reaches through a path, an exists and its where, or a path from the viewer), by the identity of each member's Entity, so two Entities of one name are told apart. It is pure, reads no Model and sends nothing.

ts
Reach.match(reaches(RenameCategory, InToys), {
  Reads: () => 'the write can change this list',
  Unaffected: () => 'it cannot',
  Unknown: ({ why }) => `the declarations do not say (${why})`,
})

write is a Write, or a mutation declared with Mutation.write. Unknown is never Unaffected: NoBody is a query declared with Query.make, whose meaning is its server's, and Handler is a mutation declared with Mutation.make, whose writes only its handler knows (when both apply, Handler is named). explain lists, as reachedBy, the registered mutations whose write Reads the list; a handler mutation is never listed. The answer says what a declaration allows, not what a given invocation changed, so a Reads is a possibility and Unaffected is a guarantee.

A mutation that is no Write may carry a footprint (MutationDescriptor.footprint). A Declared footprint covers in-place updates of the fields it lists, and nothing else: a command that creates or deletes rows, or changes relations, must declare Footprint.unknown, or reaches reads it Unaffected for a list the command does change and reachedBy under-reports. reaches serves explain, not the refresh after a mutation, which does not read it.

What became of a write

Data.mutation(model, requestId) reads what became of it from the Model: Pending, Applied, Failed with the error the server or transport gave, or Unknown for an id never started here (or settled so long ago it left the bounded ledger). A retry reuses its id, and the latest outcome wins.

A request id names a request to this client only: it is a counter in the Model, so it restarts on reload and two clients' first requests share it. To a server, a mutation is named by its operation, an id minted where it is first sent (crypto.randomUUID()), unique across clients. A failed request keeps its operation, and a retry with the same requestId (Data.mutate(model, M, input, { requestId })) sends it again, so a server that keeps a record of its writes can recognise the retry. After a reload the record of it is gone, and the same request id is a new operation.

When a write fails

A write that fails releases its optimistic layer, so its change disappears. Remote keeps the failure in the ledger, with the mutation and the input it was started with, until the application answers it. The application reads it from the Model; it keeps no list of its own:

ts
// The view: a notice for each post that did not send, with its text to give back.
Data.failedWrites(model, CreatePost) // ReadonlyArray<{ requestId, mutation, input, error, refusal }>

// update
case 'ClickedRetry':
  return Option.match(Data.retry(model, message.requestId), {
    onNone: () => ({ model }),
    onSome: started => ({ model: started.model, commands: [started.command] }),
  })
case 'ClickedDiscard':
  return { model: Data.dismiss(model, message.requestId) }
  • Data.failedWrites(model) lists every failed write, oldest first, and Data.failedWrites(model, CreatePost) only that mutation's, with its input and refusal typed by it. A write in flight or applied is not listed.
  • Data.retry(model, requestId) sends a failed write again as itself: the same input, request id and operation, with its optimistic change shown again. It is None for a write that is not failed, so a second press does nothing.
  • Data.dismiss(model, requestId) forgets it.

Only a write in flight can fail: a MutationFailed repeated, or arriving after the write applied, was dismissed or was settled by forget, returns the Model it was given, as a repeated MutationSucceeded does.

A failed write stays listed until one of those, or Data.forget at a change of principal. Nothing drops one on a timer: that would hide a failure the reader has not seen. The ledger is bounded (the last 1024 failures), and is never persisted, so a reload forgets it.

To act on a failure in update (log it, move focus, put text back), have the wiring share it. Remote reduces it first, then the application's own update receives it with a Model that already lists it:

ts
Page.assemble(Data.wiring(actives, { shared: ['MutationFailed'] }))
// own update: MutationFailed is now one of its Messages, so its match must answer it

A wiring that does not share it records each failed write as a WriteUnheard diagnostic, which by default logs it: the change went, and nothing in the application's update was told.

Refused for who asks. A server may also refuse who is asking, whatever the mutation (RemoteServer.forbid). Then Data.mutation(model, requestId) is Failed with an error of _tag: 'Forbidden', and reason when the server gave one, for the person who asked. Asking again as the same person is refused again, so show it rather than retry.

Refusals as data. A mutation can say what the server may refuse it with, as data rather than a message to parse:

ts
const SetPrice = Mutation.make('SetPrice', {
  Input: { id: Schema.String, price: Schema.Number },
  Output: {},
  Refusal: Schema.Union([Refusal.field('price', Schema.String), Refusal.conflict]),
})

Data.refusal(model, requestId, SetPrice) // Option<{ _tag: 'Field', key: 'price', reason: string } | { _tag: 'Conflict' }>

Refusal.field(key, reason) names an input key and the Schema of why; Refusal.conflict says the row moved on, and Refusal.unmet that it does not hold what a declared write's when asks of it. A Mutation.write is refused as unmet only when its write has a when, and its Refusal type says so: without one it stays Conflict, so a match over it needs no Unmet arm. Refusal.taken says an insert's id is already a row's: its entity and id, the caller's own, and nothing of the row, which may be hidden from them. A Mutation.write over Write.insert is refused as taken and never as a conflict, since an insert expects no revision. Refusal.invalid says the row it would leave breaks an invariant of its Entity (Entity.invariant): its entity and rule (an id is unique only within its Entity, so the two name it) and its path, which a form shows the message beside, or none and empty when the invariant reads something the caller may not see. Every Mutation.write may be refused so, since the server's Entity may hold invariants the client's does not show. Refusal.isInvalidBy(refusal, invariant) asks whether it names one invariant, by its Entity and its id, given as Entity.invariant returned it (export it beside the Entity), so its id is never spelled again; an unnamed refusal matches none, and so does another Entity's invariant of the same id. The server sends the refusal encoded by this schema and Data.refusal decodes it by the same one; it is none while the mutation is pending or applied, or when it failed for another reason.

Declared writes: what the client predicts

A mutation can be a declared write. Mutation.update(name, Entity, { set }) declares one in a call: its input is the Entity's id, naming the row, beside each field set names by its key, with the schema the input holds it with (Entity.fields(Project, 'name') for the field's own). Mutation.insert and Mutation.delete are the other two kinds, and the options (when, from, becomes, expect, increment, decrement, compute) are the write's. An update's input holds keys about the operation alone, each mapped to no field, which increment, decrement, compute and when read: Mutation.update('Deposit', Account, { input: { amount: Schema.Number }, increment: { balance: 'amount' } }). A key in both set and input, or the id in input, is refused at the key and where it is declared.

ts
import { Mutation } from 'foldkit-remote'

const EditProject = Mutation.update('EditProject', Project, {
  set: { name: Schema.String, status: Schema.String },
})
Data.mutate(model, EditProject, { id: 'p1', name: 'Apollo II', status: 'active' }, { keys: ['name'] })

Building it sends nothing and runs nothing: it is a declaration a page registers with Remote.make and a server with RemoteServer.write. It is the long form Mutation.write(name, Write.update(Entity.input(Project, input), { id: 'id' })), the same value, whose three calls each own a part: Entity.input says which input key is which member (a Form is built from it alone), Write.update says what the write does to the row (foldkit-entity's, which Laws.check and every writer read), and Mutation.write names it, types what it may be refused with and installs the prediction below. Write the long form when an input key is named otherwise than its field, or points a relation (Relation.input); a key about the operation alone (Entity.unmapped, an increment's amount) is the short form's input.

Its input is the write's, it answers nothing of its own, and Data.mutate shows an update's or an insert's row until the server answers, so it needs no optimistic list; a delete shows its row deleted, as Remote.tombstone does. An update's increment (and decrement, its amount negated) is shown as a prediction: its amount is added to the value the store holds whenever the row is read, so a change that reaches the store meanwhile is added to rather than hidden, and two pending increments add up. A computed field is predicted the same way, by Remote.make's operators over the row as it is read (Write.apply), so a live change to what it reads changes the prediction. So is a count another registered Entity derives over the written row's relation (likeCount: Derived.count(Like.relations.post)): inserting a Like adds one to the post it points at, deleting a Like the client holds takes one away from the post it pointed at, and pointing it elsewhere does both, each added as an increment is. Where the client does not hold where the row pointed, or holds no count on that post, nothing is predicted.

A write shows what its Entity sets from the context (Entity.sets) as well, which no input sets: Expr.viewer as the viewer Remote.make is told of, and Expr.now as Data.mutate's now, the time the reader acted. An insert sets every such member, an update those set on: 'write' (an editedAt). A new row's counts read 0 and its exists none.

update reads no clock, so the time is read where the action is, by a Command, and carried in the Message that starts the write. Remote.now(toMessage) is that Command; it reads Effect's Clock, so a test pins it:

ts
// the action asks for the time…
Posted: ({ post }) => ({ model, commands: [Remote.now(now => Message.Clocked({ post, now }))] }),
// …and the Message it yields starts the write with it
Clocked: ({ post, now }) => {
  const sent = Data.mutate(model, PostChirp, post, { now })
  return { model: sent.model, commands: [sent.command] }
},

The request sends the same number, and the server takes it as the row's time when it lies within its clockSkew of the server's own clock (60 seconds unless RemoteServer.make says), so the answer agrees with what was shown. A retry (Data.retry) sends it again. Without now, a time the write sets is not predicted: the row reads as missing it until the server's answer brings the server's time. A supplied member declared with a predict (Derived.make(schema, { predict }), as Guard's may is) is foreseen over the row the write leaves, the store's row with the write's values over it and a field the write moves unknown; where it foresees none, the row reads as missing it until the answer. An application that already mints the row's id in a Command can read the clock in the same one (examples/reference's NameNote). The row then joins every loaded list whose body admits it, where the list's order puts it, while pending and once answered: a post set at its time goes to the top of a newest-first list. A list without a body, or one filtered by a read rule the client does not run, is the server's to place.

A viewer-relative member is predicted for the viewer Remote.make is told of. With a Like pointing at a Post and a User (examples/chirp declares the whole domain, its writes and its server):

ts
const Post = Social.Post.pipe(
  Entity.derived({
    liked: Derived.exists(Social.Like.relations.post, { viewer: Social.Like.relations.user }),
  }),
)
const Data = Remote.make({
  model: App.model.remote,
  entities: [User, Post, Like],
  mutations: [LikePost, Unlike],
  viewer: model => Option.some(Remote.ref(User, model.me)),
})

liked is the id of the viewer's Like of the post, or none. Inserting a Like pointing at a post and at the viewer shows it on that post (where the post is held with liked read, and none yet); deleting a Like, or pointing it at another post or person, takes it from the post it is shown on. That post also says where the deleted Like pointed, so its count goes down with no Like row held: unliking is Data.mutate(model, Unlike, { id }) with the id liked holds. The store holds one viewer's values, as it holds one principal's, so a change of viewer is a change of principal: Data.forget.

A field the client has not read, or a computation by an operator its table lacks, is not guessed; it shows the server's value when the answer comes. The prediction is never authority: the server decides, and its answer replaces it. The declared writes guide follows one write from here to the statement that lands it. keys names the input keys an author changed: only those are shown, and the request carries them for the server to write; the input is still sent and validated whole.

Data.can(model, Mutation, input) tells, before anything is sent, whether the server would refuse a declared write, from what the Model holds. It answers a metakit Verdict (read it with Verdict.match from @doeixd/metakit): False, whose witness is the refusal, Forbidden (a held may), Unmet (the when) or Invalid (an invariant), checked in the server's order; Unknown with its reasons where the row, a field it reads, a may member or an input key is missing; otherwise True. It is a hint to grey a control: Data.mutate does not read it, and still asks the server. See Asking before sending. Data.capability(Mutation, toInput) and Data.available(Mutation, inputOf) turn the same answer into a foldkit-agent capability's authorize, applies and available (Agents). They judge as the Model's viewer: as an agent's only authorize they give it the viewer's write rights, so compose them with a check of the agent's principal.

Refused where it is made

Before it shows or sends a declared write, Data.mutate refuses the ones the client can already tell the server would refuse, in the order the server checks: who asks, then the row.

A write the held may says no to. A supplied member may say which write its value forbids (Derived.make(schema, { forbids })); Guard's may does: the row's Update or Delete, a written member's own rule, or a relation's Link or Unlink, where it reads false for the row as the store holds it. Data.mutate asks each such member it holds before it judges the invariants, as the server refuses who asks first, and answers MutationFailed with _tag: 'Forbidden' and the explain's words as reason, showing and sending nothing. A may not held, or one that does not name the part, refuses nothing; a held may is the server's answer as of its read, so Data.refresh asks again.

may is a UI hint, and the server enforces every write. A may that says yes, stale after a change of role, foreseen for a row the client wrote, or edited in the page's Model, decides nothing: the request carries no may, the server checks the write by its rules as the request's principal, and a refusal comes back as Forbidden, which takes the shown change back. The client's refusal only saves the round trip for a no it already holds. See foldkit-guard for what may tells a reader.

A write the client can tell is invalid. Data.mutate judges a declared write's Entity invariants over the row it would leave, as the client holds it: the store's row with the write's values over it, a field it moves (an increment, a computed value) not held. Where one is definitely broken, it shows nothing and sends nothing; its Command answers MutationFailed at once with the very Refusal.invalid the server would send, so Data.refusal, Data.failedWrites and your update handle it as a server's. An invariant over a field the client lacks is undecided and refuses nothing: the server judges it. Passing optimistic yourself skips the check.

What an answer carries

When the answer comes, the request's layer comes off, so the answer must hold everything the layer showed. The client says what that is: Data.mutate sends, with the request, what every active Surface reads of each entity (each Data.get's fields and each Data.query's select, relation targets included), and every field the layer itself shows. The second matters when a write moves a count no Surface reads now: a note deleted on its own page lowers its author's noteCount, which only the notebook page reads, and without it the answer would leave the count as it was before the write. It also sends, for a created or edited row, every supplied member its Entity foresees (Derived.make's predict, Guard's may), foreseen this time or not: a page opened on a new note before its add is answered reads its may, though no Surface did when the add was sent. The server reads, of each row its answer names, the fields it shows that the answer left out, after the write and as any read is, and sends that read with the answer (foldkit-remote-server's What an answer carries). The client merges the answered rows and read fields into the store and releases the optimistic layer in one reduction.

So a created post lands with the count, the may and the author's name the feed reads, though the write stored none of them, and the feed never reads Loading for it. There is nothing to configure: the Surfaces already say what is shown. A row the answer does not name is not read; the server names the rows a write changed. Each Data.subscriptions call registers what it reads, so a Data.mutate with none registered sends nothing to show.

When the server's reads lag its writes: revisions and read-after tokens

Some servers answer a read from a copy that catches up after a write: a Domain View, a database read replica. Two optional wire fields keep such a server from showing a row older than one the client already holds:

  • Row revision (NormalizedEntity.revision, EntityPatched.revision): an answer with a lower revision than the stored row writes nothing.
  • Write token (MutationResult.after = { token, rows }): each named row is held to that token floor until a read at that token answers.

The store keeps both beside the row (EntityEntry.revision, .floor), so a snapshot persistence restores keeps them, as does a server render's capture (Remote.resume), and nothing else owns them. Only a domain that registers a Mutation reads with tokens: a page that writes nothing carries none of that code, and keeps a floor a snapshot brought without asking at it. The server owns what they mean: Remote only compares revisions and sends a token back. While a row has a floor:

  • the read entry reads it again, even with every field held, and the read carries its token (ReadBatch.after, at most MAX_READ_AFTER = 256 rows; the rest wait for the next plan);
  • an answer read at the token, or one of a newer revision than the row held (the server has it past the write), writes the row and ends the floor; a row the server names in behind (its copy has not caught up) keeps what the store holds and the floor, and is asked again with the token after a wait (1 second, doubling with each answer behind, at most 30; EntityEntry.behind, not persisted, so a reload asks at once); any other answer to a read asked without the token writes nothing of the row;
  • a live stream subscribes with the tokens of the rows it watches (LiveRequirement.floors), and restarts when they change. A server sends a floored row's patch only once it reads at the token, so a patch on a stream opened at the row's token, or one of a newer revision, writes it and ends the floor, and any other on a stream opened before writes nothing of it;
  • a live stream also names the revision it holds each row at whole, with no field stale and no floor (LiveRequirement.revisions), as it starts; a moved revision does not restart it. A server may leave out a row's state at or before that revision, which the store has: a page resumed from a server render opens its stream without being sent back what it was handed;
  • Data.inspect(model).floors lists them, and why names the wait (ReadAfter).

A tombstone keeps the revision the row was gone at, so a late answer to a read begun before it went does not bring it back; a server whose revisions restart when a row is created again should send none. A tombstone asked about again (Data.refresh, a freshness running out) takes a row of that revision: a row a read left out because the reader lost sight of it comes back unchanged once the reader may see it again. foldkit-remote-drizzle's source sends the bound revision (source(binding, { revision })); foldkit-remote-domain sends both.

Checking an answer against what was shown

When the answer comes, the request's layer comes off, and what the row shows is what the store holds. Two things can then differ from what was shown. Remote.make({ ..., verifyPredictions: true }) settles every mutation as usual and records each as a PredictionMismatch diagnostic, its part naming which:

  • Value: a field the layer showed that the answer carries another value of. The client's prediction and the server's write disagree: a count moved by two, a time from another clock, a hand-written optimistic patch that guessed. A field another pending request also shows is not judged, since that request's value shows before and after.
  • Gap: a field the layer showed that the answer left out, and the store does not hold. It is then missing: an active Surface that reads it fetches it again, and the row reads Loading meanwhile.
ts
// requestId: the one Data.mutate returned; mutation: its name
{ _tag: 'PredictionMismatch', part: { _tag: 'Value', requestId, mutation, entity: 'Post', id: 'p9', field: 'likeCount', shown: 3, answered: 4 }, … }
{ _tag: 'PredictionMismatch', part: { _tag: 'Gap', requestId, mutation, entity: 'Post', id: 'p9', fields: ['editedAt', 'author'] }, … }

Match on the part with PredictionPart.$match. Law.check (below) is the same law, in a test, over every part rather than the ones an answer carries.

A list a declared insert cannot draw in is named where it is read. A row a pending Write.insert makes holds its id, what its input maps, what its Entity sets on create (Entity.sets), its counts and exists, and what a supplied member foresees. A list that selects anything else of it (a nullable editedAt no input names, a relation) cannot draw the row until the answer, and reads Refreshing meanwhile. Under verifyPredictions, Data.query reports that as an InsertUnpredicted warning, once per list, insert and members:

[foldkit-remote] Feed selects Post.editedAt, which CreatePost cannot predict: a Post it makes is not shown in Feed until the server answers, and Feed reads Refreshing meanwhile. Map it in CreatePost's input, set it with Entity.sets, or select fewer.

It is reported to the default reporter (Effect's log), since no application's context reaches a declaration, and it is not recorded in the Model. An optional input key counts as mapped, though a write that leaves it out shows no value for it.

A row's shown fields are those the request's optimistic patch wrote, added to or computed (a declared write's own included), plus those the active Surfaces (every Data.subscriptions call) read of a row the request patched or put in a list. A field the store still holds (an older value, or another pending request's) is not reported, nor is a row the answer deleted, or a temporary id it replaced. A repeated answer is not checked again. With the answer's read, a gap is a row the answer did not name: name it in the answer's entities (Remote.patch(Post, id, {}) asks the server for all it shows of it).

On in development and tests, off in a build. It changes nothing but diagnostics and fetches each placed list once more, and no package reads a build mode, so the application says it where it declares the domain:

ts
const Data = Remote.make({
  model: App.model.remote,
  entities: [Post],
  queries: [Feed],
  mutations: [PostChirp],
  verifyPredictions: {
    // Vite's dev server and Vitest set DEV; a production build does not, and tsx has no import.meta.env.
    on: import.meta.env?.DEV === true,
    // What the server is meant to answer otherwise, each with why: recorded as nothing.
    expected: {
      mutations: { PostChirp: { Value: 'the server stamps createdAt with its own clock' } },
      queries: { Feed: { Placement: 'the server ranks the feed' } },
    },
  },
})

verifyPredictions: import.meta.env?.DEV === true is the plain form. A PredictionMismatch is reported at error level, so the default reporter writes it to console.error, which a browser test and Behaviors.consoleErrors see. expected names the domain's own mutations (Value, Gap) and queries (Placement): another name is a type error, a blank reason is refused where the domain is made, and the silencing is in the declaration, where a review reads it. A test does not assert on diagnostics by hand: Trace.run fails on any mismatch.

Showing a change nobody has made

A mutation's optimistic operations show over the store while it is in flight. overlay from foldkit-remote/overlay shows operations the same way with no request behind them, until lift: a preview, in every Selection and view, of something not yet sent. They are functions of the domain rather than its methods, so a page that never previews loads none of the code that shows one.

ts
import { lift, overlay } from 'foldkit-remote/overlay'

const previewed = overlay(Data, model, 'post-preview', [
  Remote.patch(Project, id, { name: draft }),
])
const back = lift(Data, previewed, 'post-preview')
  • Both are called from update, and neither performs I/O or touches what the server said: the store beneath is as it was.
  • Showing an id again replaces what it showed. Lifting what was never shown returns the same Model.
  • An overlay's id is apart from every request's, so a mutation that settles does not take a preview with it.
  • A preview of an entity the server has not seen, such as an unsaved post, has only the fields the overlay holds. A Selection that reads more reads Failed, with an Overlaid error naming what is missing, since nothing will fetch it. Overlay every field the Selection reads, or preview through a smaller Selection.
  • overlays(Data, model) lists the ids shown now, in the order they are drawn. A caller that overlays from state of its own reconciles against it: foldkit-sync/remote shows a replica's pending cell edits this way, so the durable edit stays Sync's and Remote only draws it.

Reading past what is only pending

Every projection reads the visible cache: the server-derived store under the layers still pending, which is why an optimistic change shows at once. A reader that must not believe a change until the server has agreed to it asks for the confirmed read instead:

ts
Data.confirmed(Data.get(ProjectSummary, projectId))

It is the same projection — the same requirements, planned the same way, so observing it fetches exactly what observing the original fetches — reading the server-derived store alone, with the pending layers and connection overlays left off. An optimistically inserted edge is not in its page; an optimistically patched field reads as the server last said.

A view almost always wants the projection itself. This is for the reader that reports on the world rather than drawing it, which in practice is an Agent capability that must not claim success before the server reflects it:

ts
import { Agent } from 'foldkit-agent'

Agent.when({
  projection: Data.confirmed(Data.get(ProjectSummary, projectId)),
  // The projection reads a RemoteData: only a value the server holds can match.
  predicate: (project, request: { readonly name: string }) =>
    RemoteData.render(project, {
      loading: () => false,
      notFound: () => false,
      failed: () => false,
      data: value => value.name === request.name,
    }),
})

There is deliberately no Data.visible: a projection already is the visible read, and a second name for it would be a wrapper that only forwards.

Sync draws the same line over its replica, with the same words and a different mechanism: see what a reader sees while a change is in flight.

A write that outlives the page: outbox

A like pressed on a train, a post written in a tunnel: the write must reach the server, but nothing needs to converge, since the server decides it once. Make it durable, and assemble the outbox beside Data.wiring:

ts
import { outbox, outboxStatus } from 'foldkit-remote/outbox'

const durable = outbox(Data, {
  key: model => `outbox:${model.userId}`,
  scope: model => model.userId,
})
const placements = Page.assemble(Data.wiring(actives), durable)

// update: queued, not sent; its layer shows at once
const queue = (model: Model) => {
  const sent = Data.mutate(model, PostChirp, post, { now, durable: true })
  return { model: sent.model, commands: [sent.command] }
}

// the view
const { waiting, waitingForSignIn } = outboxStatus(Data, model) // "3 changes waiting"

// update, once the application knows who is signed in again
const signedIn = (model: Model) => ({ model: Data.signedIn(model) })

waiting counts a write on its way too, so a line drawn whenever it is above zero shows for a frame or two on every write, pushing the page below it down and back. Draw it once a send went unanswered: that is writing's Unanswered (below).

durable.restore(model) is cache.restore's twin: resolve it as the runtime's flags and start init from it. It reads back what a reload left and mints the page's session, which names its writes; Data.mutate with durable before it has run throws.

A page a server rendered (foldkit-ssr's SSR.hydrate) runs no init and must first draw what the server drew, which cannot include a queue only this browser stored. It resumes from durable.session instead, which mints the session and reads nothing, so a durable write can be made at once; the outbox's own Subscription reads the queue after the first frame, and its OutboxRead keeps any write made before it:

ts
SSR.hydrate(config, plan, { buildId, prepare: durable.session })

See what only the browser has in foldkit-ssr.

How the durable lifecycle runs:

  1. Data.mutate(..., { durable }) queues the write in the Model, shows its optimistic layer, and emits MutationQueued.
  2. outbox.save writes the queue to storage, merges with other tabs, and emits OutboxRead.
  3. outbox.send sends the oldest stored write one at a time from one tab, settling with MutationSucceeded or MutationFailed (or moving to WaitingForSignIn on Unauthenticated or PrincipalChanged until Data.signedIn resumes it).
  4. outbox.adopt / outbox.hold reassigns visitor writes on sign-in (OutboxMoved) or holds writes belonging to another principal (OutboxHeld).
  5. On page reload or SSR (durable.session), outbox.restore reloads the queue, restores the optimistic layers, and resumes sending with the same operation ID and now.
  • Stored before sent. A write is sent only once the store holds it, so a reload while it is on its way finds it and sends it again. Its request id is its operation id, so the writer's ledger answers the second send from its record: a durable Mutation needs a ledgered writer (RemoteServer.write, or remote-drizzle's writer), or a handler that answers by operation id.
  • In order, one at a time. A post and the like of it, made offline, reach the server in that order. A refused write, or one this version cannot read, does not hold back the rest.
  • Sent again only when nothing answered. A send that fails with Unreachable (the request did not go, or what came back was no Remote answer) keeps the write waiting and sends it again after 1 second doubling to 30 (retry: { base, max }), and as soon as the browser is online; each attempt is OutboxDelayed. A refusal, Forbidden or a server error settles it as Failed, as for any write: Data.failedWrites, Data.retry (queued again) and Data.dismiss (gone from the store too) work on it unchanged. A write still waiting cannot be dismissed: it may be on its way.
  • A session that ended waits for a sign-in. Forbidden is a person the server refused, and is final; Unauthenticated (a 401) is a server that could not tell who sent it: a session that ended, or a visitor, which GuardServer and RemoteServer.write refuse with it rather than Forbidden. A write so answered stays queued as WaitingForSignIn in outboxStatus (waitingForSignIn counts them), its layer still shown and its ledger entry pending, and every write after it waits behind it, in order. Nothing sends it again on its own, a reload included: once the application knows who is signed in (its sign-in answered, or a reload read who it is), update reports it with Data.signedIn(model), and the outbox sends it again as itself, then the rest. It sends only the queue of the scope the page holds, so call Data.signedIn after moving scope to the person who signed in: a sign-in as someone else reads their queue, never this one. It cannot be dismissed while it waits. A handler of your own (RemoteServer.mutation) refuses a visitor with RemoteServer.unauthenticated(reason) for the same.
  • Made for one person. Every answer says whom it was for (principal, from the server's viewer), and a durable write is stamped, when it is queued, with whom the last answer named. It is sent naming them, and the server runs it for no one else: under a stale scope and another person's cookie it is refused before it runs (PrincipalChanged) and waits, as WaitingForSignIn with that error, until Data.signedIn finds them signed in again. A replay of a write already run is answered to them alone. A retry keeps the stamp it was made with. A queue is owned by the first person signed in heard under its scope; a write made while the page last heard a visitor (a cookie dropped) is its owner's, when someone owns it, so Ada's edits stay Ada's. The owner is saved with the scope's queue, so a reloaded page, offline or before its first answer, stamps its writes as them. An answer to a request sent before Data.forget is not heard: it was for whoever the page forgot. A write to a server with no viewer names no one, and nor does one queued where the scope's queue has heard no one yet.
  • Held when the cookie changes hands. When an answer names someone other than whom the queue's writes were made for, while the scope stays, the outbox sends none of them, nor any after them: outboxStatus shows each as WaitingForSignIn with a PrincipalChanged error, and each page that hears it says so once with OutboxHeld { requestIds, scope }. An answer naming them again sends them, in order.
  • A visitor's writes go to whoever signs in first. A write made with no one signed in (the last answer said a visitor, and no one owns the queue) is sent as a visitor's (principal: null), which the server runs only for a visitor: sent after someone signed in, by any tab, it is refused unrun and waits. Once an answer names who signed in, the outbox moves the visitor's waiting writes from the queue the page held before into the one it holds now, stamped as that person, and sends them. Where the scope did not move, it stamps them in place, with any write queued before an answer said who, and sends none of them unstamped as that person. The tab that moved them says so once with OutboxMoved { requestIds, from, to } (the scopes, one scope in place), which update reads before reducing, or with Data.wiring(…, { shared: ['OutboxMoved', 'OutboxHeld'] }) under an assembly, to tell the person. Nothing moves out of a queue someone signed in owns, a refused write never moves, and nothing moves before an answer names who.
  • One tab sends; every tab shows. The store is shared by every tab on the key. A Web Lock picks the one that sends, which reads the store again first so a write another tab settled is not sent twice; a BroadcastChannel tells the others, which show each other's waiting writes and settle them with the sender's answer. Without Web Locks each tab sends what it holds.
  • now is the reader's, still. A stored write is sent with the time it was made at. Past the server's clockSkew, the server writes its own time and reports ClockSkewed, and the answer moves the row there: the bound that stops a client backdating rows cannot tell an honest wait from a forged one.
  • After a deploy. A stored write naming a Mutation this version lacks, or whose input no longer decodes, is kept as Unreadable in outboxStatus, never sent, reported once as OutboxUnreadable, and removed by Data.dismiss. A store that cannot be written reports OutboxUnsaved, and the writes are sent anyway.
  • A change of principal is Data.forget and another key, as for persistence: one person's waiting writes are never sent as another's. The page holds the queue it read for one key and scope; when either moves, it sends none of it and reads the new one's. A store holding another scope's waiting writes is not written over, so a key shared by principals reports OutboxUnsaved rather than losing them.

What is being saved: writing

A view that dims a row or says "waiting to send" asks one question: is something I wrote still unanswered, and how badly? The ledger and the outbox already hold the answer, so writing derives it, and nothing in the application's Model copies it (a flag the application writes would be wrong after a reload, which restores a write no click made, and in a second tab):

ts
import { Writing, writing } from 'foldkit-remote'

const savingLine = (model: Model): string =>
  Writing.match(writing(Data, model, { mutation: PostChirp }), {
    None: () => '',
    // Every write passes through here: a line for it would flash on each one.
    Sending: () => '',
    Unanswered: ({ requestIds }) => `${requestIds.length} waiting to send`,
    WaitingForSignIn: () => 'Sign in to send your changes',
    Unreadable: () => 'Some changes cannot be sent from this version',
    Failed: () => 'Some changes were refused',
  })

writing(Data, model) reads every write of the domain; the filter narrows it to { mutation }, the Mutation as Data.mutate was given it (not its name; one the domain does not register throws), and { row }, an EntityRef (Remote.ref(Post, id)), the writes whose pending layer patches or deletes that row. A refused write shows no layer, so it is Failed for the domain and for a mutation, and in no row. It is a pure read: it sends and writes nothing, and a page that never calls it keeps none of it.

The worst state among the matching writes is the answer, in this order, and requestIds lists the writes in that state alone:

StateA write that isDo
Failedrefused by the serverData.retry or Data.dismiss it
Unreadablestored by a version this one cannot readData.dismiss it
WaitingForSignInheld until Data.signedIn hears a sign-inask for one
Unanswereddurable, sent, and no answer yet, so the server may have it; error is why the last send faileda "waiting to send" line
Sendingon its way for the first time, or a plain write awaiting its answernothing

Sending is every write's first state, which is why a "waiting to send" line reads Unanswered. It is built from the same reading as outboxStatus, which stays the list of durable writes, with each one's error; writing is the one state a view matches on. Its ids are request ids, the ones Data.mutate returned and Data.mutation and Data.dismiss take: a durable write's operation id is its request id. Plain writes come in the order they started, then durable ones in the order the outbox sends them.

Remote mutation vs Sync operation

A durable Remote write is still Remote's: the server decides it once, a refusal is final, and the client never reads its own effects before the server has answered. If edits must merge with other devices' edits made offline, or the application must build on its own unsent edits as if they were committed, that is foldkit-sync's journal (see which state belongs here). An optimistic overlay stays a temporary view of server-owned data: the outbox stores the operation, never the overlay as a queue of edits.