The engine behind every write: read → fold → decide → append, with DCB and optimistic concurrency.
On a concurrency conflict it repeats the whole cycle (re-read, re-fold,
re-decide, re-append). Same when FACT answers :index_timeout: before
checking the condition, FACT (0.4.2+) waits for every index to reach the
ledger, and if they don't in time it gives up without writing anything.
Reading what you just wrote
Fact.append/3 confirms the append a few milliseconds before the event is
visible to a subsequent read (measured: 7–10 ms). If your app is LiveView and
a handler writes and then immediately re-reads to repaint, without a wait
the user clicks and the page still shows the old state.
So execute/4 doesn't return until the event it just wrote is visible to a
read. The wait lives here, in the one place every write passes through, rather
than being scattered across handlers. It costs a few milliseconds per command,
and in exchange everything above can assume what it wrote is there.
Where the append condition is anchored, and its ceiling
The append is conditional: "fail if any event matching this query appeared
after position P". Today P is the position of the last folded event,
which is 0 when there's nothing to fold — and for a brand-new entity that
is the normal case, because nobody has written about it before.
With P = 0, FACT scans the entire ledger applying the query, inside the
handle_call of the single writing process. It's linear in accumulated
history. Measured:
ledger of 531 events → decide 29 ms
ledger of 7,591 events → decide 256 ms
ledger of 37,651 events → decide 1.1 s
ledger of 157,711 events → decide 4.5 sIt isn't solved here on purpose, because most systems never reach those
numbers. When it starts to hurt, the seam is read_and_fold/3: have it
return max(visibility_mark, last) instead of last, where the mark is the
position up to which every FACT index has caught up (FACT announces it over
PubSub as {:indexed, position}).
Ask for the mark before reading, not after: that way everything the read can return sits below it, and the condition still watches from the mark onwards — which is where a concurrent writer would be. With that, the same decision over 157,711 events drops from 4.5 s to 8 ms.
And the anchor can't be the head of the ledger: Datumo.Reader reads by
index, and FACT's indices are maintained asynchronously. Anchoring at the
head would be claiming to have seen events the index hadn't published yet.
Summary
Functions
The read-and-fold loop, with the read passed in: decider.query(cmd), then
next_query/1 until nothing new, folding with apply_event/2.
Functions
The read-and-fold loop, with the read passed in: decider.query(cmd), then
next_query/1 until nothing new, folding with apply_event/2.
Returns {state, last_position, first_query_items, every_query_item_read}.
Production reads FACT; Datumo.Scenario reads the scenario's given, so a
test runs this same loop and a wrong query fails the scenario.