Logging and replaying a session
An append-only log, a replay up to time t, fingerprints, and the snapshot that forgets the rank counter.
Lesson 1111 min
By the end of this lesson
- Rebuild the book at a given moment by replaying the log
- Compare two sessions by their fingerprint, where execution order matters
- Explain why the log and the snapshot must keep the ranks
In this lesson6
The lesson An engine's invariants set out determinism: the same sequence of inputs always produces the same sequence of outputs. This property has a practical consequence. If you keep every input, in order, you no longer need to save the book: you can rebuild it at any moment of the session. This lesson builds that log, replays it, and shows the exact place where a recovery can go wrong.
Event log
An ordered, append-only list of the inputs received by the engine, which is enough to rebuild its state.
What the texts say
Two market rules point this way. Every order is timestamped as soon as the brokerage firm receives it (BVMAC General Rules 2025, art. 150). The 2008 draft market rules gave each order an acknowledgement and "a sequential order number per security" (Instruction no. 2, 2008, section 3). On the messaging side, a FIX session numbers its messages in a continuous series from 1 and provides for their resynchronisation (FIX Session Layer).
We found no reliable source describing how a real platform logs, snapshots or replays a session. Everything that follows (log format, replay, fingerprints, recovery) is a design choice of the teaching engine, presented for its reasoning.
A log around the engine
The @criee/marche engine logs nothing. We wrap it in a class that writes each event before applying it:
import { Carnet, type Execution, type Ordre } from '@criee/marche'
type Evenement =
| { n: number; type: 'passer'; ordre: Omit<Ordre, 'rang'>; rang: number }
| { n: number; type: 'annuler'; id: string }
class MoteurJournalise {
readonly journal: Evenement[] = []
private readonly carnet: Carnet
private dernierRang = 0
constructor(prixReference: number) {
this.carnet = new Carnet(prixReference)
}
passer(ordre: Omit<Ordre, 'rang'>): Execution[] {
const ev: Evenement = { n: this.journal.length + 1, type: 'passer', ordre: { ...ordre }, rang: ++this.dernierRang }
this.journal.push(ev) // write first
return this.carnet.passer({ ...ordre, rang: ev.rang }) // then apply
}
annuler(id: string): boolean {
this.journal.push({ n: this.journal.length + 1, type: 'annuler', id })
return this.carnet.annuler(id)
}
}
Three decisions are visible. The number n orders all events, orders and cancellations alike. The rang is assigned by the wrapper and written into the log, instead of being left to the Carnet's internal counter. And { ...ordre } copies the order: if the caller later changes its object, the log does not move.
Replaying up to time t
Replaying means applying the log's events, in order, to a fresh book. The state at time t is the replay of the first t events.
function rejouer(journal: readonly Evenement[], prixReference: number, jusqua = journal.length) {
const carnet = new Carnet(prixReference)
const executions: Execution[] = []
for (const ev of journal.slice(0, jusqua)) {
if (ev.type === 'passer') executions.push(...carnet.passer({ ...ev.ordre, rang: ev.rang }))
else carnet.annuler(ev.id)
}
return { carnet, executions }
}
Replay
Applying a log's events again to a fresh engine, to rebuild a state or check outputs.
A session of seven eventsFictional
Buy a1 of 20 at 10,000, sell v1 of 30 at 10,100, buy a2 of 15 at 10,000, sell v2 of 10 at 10,000, cancellation of v1, buy a3 of 10 at 10,000, sell v3 of 30 at 10,000.
rejouer(journal, 10000, 4).carnet.vue() gives, at time 4: on the buy side one level at 10,000 for 25 shares (a1 reduced to 10, plus a2), on the sell side v1 at 10,100 for 30. The full replay returns four executions: a1 and v2 for 10, then a1, a2 and a3 against v3 for 10, 15 and 5.
From memory: is the book state at time t data to save, or a computation?
Fingerprints: comparing at a glance
To check that a replay matches the original session, comparing lists of executions is heavy. We sum them up in a fingerprint: a short value, computed deterministically.
/** 32-bit FNV-1a: fast and stable, but not cryptographic. */
function empreinte(valeur: unknown): string {
const texte = JSON.stringify(valeur)
let h = 0x811c9dc5
for (let k = 0; k < texte.length; k++) {
h ^= texte.charCodeAt(k)
h = Math.imul(h, 0x01000193) >>> 0
}
return h.toString(16).padStart(8, '0')
}
empreinte(sortiesEnDirect) === empreinte(rejouer(m.journal, 10000).executions) // true
Fingerprint
A short value computed from a state or a sequence of outputs, to compare two runs at a glance.
The fingerprint depends on order: empreinte([1, 2]) differs from empreinte([2, 1]). That is intended. Two sessions producing the same executions in a different order are not the same session.
Snapshot and recovery: the forgotten counter
Replaying from the start gets long as the log grows. The usual answer is the snapshot: copy the state at a given moment, then replay only what follows.
Snapshot
A copy of the engine's state at a given moment, from which the rest of the log is replayed.
The teaching engine makes this move tricky. ordres() exposes the resting orders with their rank, prix exposes the last price, but nothing exposes the internal counter that will number the next order. A restored book starts again at 1. Pick a mode below, then step on to events 6 and 7.
- 1. a1 B 20@10,000
- 2. v1 S 30@10,100
- 3. a2 B 15@10,000
- 4. v2 S 10@10,000
- 5. cancel v1
- 6. a3 B 10@10,000
- 7. v3 S 30@10,000
Buys
empty
Sells
empty
new Carnet(10000)
t = 0: empty book
The computation, step by step, for the "ranks not logged" mode:
// Snapshot after event 5: a1 (10, rank 1), a2 (15, rank 3), last price 10,000
const r = new Carnet(10000)
r.passer({ id: 'a1', sens: 'achat', quantite: 10, limite: 10000, rang: 1 })
r.passer({ id: 'a2', sens: 'achat', quantite: 15, limite: 10000, rang: 3 })
r.passer({ id: 'a3', sens: 'achat', quantite: 10, limite: 10000 }) // counter at 1: a3 gets rank 1
r.passer({ id: 'v3', sens: 'vente', quantite: 30, limite: 10000 })
// [ { a1, v3, 10000, 10 }, { a3, v3, 10000, 10 }, { a2, v3, 10000, 10 } ]
// original session: a1 for 10, a2 for 15, a3 for 5
At event 6 nothing shows: the aggregated view and the executions are identical. The divergence is already there, in a rank the screen does not display, and it surfaces at event 7. That is why MoteurJournalise writes the rank into the log: recovery no longer needs the counter.
Going further
An append-only log. You do not correct a written event; you add another one, a cancellation for instance. The market applies this principle to its publications: the Official Price List may only be corrected in case of omission or error, with explicit mention of the original information (BVMAC General Rules 2025, art. 132). In a database, this means insert rights without update or delete rights.
Refusals are replayed too. MoteurJournalise.passer writes the event before calling the engine. An order of quantity 0 therefore stays in the log, and rejouer throws the same exception at the same place. This is consistent, on one condition: the replay must catch and count refusals as the live run does, otherwise it stops where the session carried on. The other choice, validating before writing, keeps a log free of refusals but loses the trace of attempts.
Time is data. The receipt timestamp (art. 150) goes into the log as a field. The engine never reads the clock during a replay, otherwise two replays diverge, as in the invariants lesson with Date.now().
The cost. A full replay costs N calls to passer, each O(n log n) for n resting orders in this engine. A snapshot every k events bounds recovery to k calls, at the price of copying the state. And a replay by a new version of the engine can produce other outputs: logging which engine version was used is a decision to make.
From memory, linking to the FIX lesson: the FIX session and the log both number their items from 1. What is the number for in each case?
Your turn
Read next: FIX Trading Community, FIX Session Layer
A question? Ask your teacher, or an AI assistant, giving it the title of this lesson.