Concurrency and session revisions
Two requests can read the same session and calculate different next states. This happens when someone opens two tabs, clicks twice or sends a second request before the first finishes. Each choice can be valid for the state it read. Your application still needs to decide which result becomes the saved session.
A conditional write saves a candidate only if the stored session still matches the revision the request read. Comparing the revision and writing the result must form one protected operation. If another request has already committed, the stale write fails and your application retrieves the current state.
Where the conflict occurs
Section titled “Where the conflict occurs”We return to the learning-path graph from Anatomy of a graph. At node 10, edge 101 selects a guide and reaches terminal 20; edge 102 selects practice and reaches terminal 30. Both are available when the context contains practiceEnabled: true.
Suppose requests A and B both read that initial state. A calculates the guide result; B calculates the practice result. If your application saves both unconditionally, the second write replaces the first. The first request may already have told its caller that the guide was selected.
The diagram labels the initial state’s comparison hash H0 and the saved guide state’s hash H1. These are short labels for opaque tokens, not values to construct yourself.
With a conditional write, A’s save succeeds because the store still contains H0. B’s save fails because the store now contains H1. B must use the confirmed guide state when responding or offering another action.
The token and the write do different jobs
Section titled “The token and the write do different jobs”In the core library, HashStateVersioning computes a deterministic hash of the complete serialized state projection, preserving its types and order. The hash identifies that state value; it is not an incrementing counter.
You can pass the hash to choose() as expectedStateHash. When the engine has a HashStateVersioning provider and a sessionId, it checks both the saved state and the input state against that token before calculating the transition. This catches a request that was already stale when the operation began.
There is still a gap between calculation and persistence. Another request may write after the check. The save therefore needs its own comparison at commit time:
| Mechanism | What it establishes |
|---|---|
HashStateVersioning with expectedStateHash |
The state being interpreted matches the expected saved value when the engine checks it. |
saveWithExpectedHash() with a non-null hash |
The saved value still matches when the store protects the comparison and write together. |
| A read after an ordinary save | The application can observe the saved result at that instant; it does not prevent an intervening writer. |
The combined comparison and write is often called compare-and-swap, or CAS. Reading, comparing and then performing an unprotected save does not provide that guarantee.
Configure a store that protects the commit
Section titled “Configure a store that protects the commit”The core ConditionalSessionStoreInterface adds createIfAbsent(), getStateHash() and saveWithExpectedHash() to the session-store contract. LockingSessionStore implements it by locking a session key, reading the actual backing store, comparing the expected hash and writing while the same lock is held.
For a file-based application on one host, the example uses FilesystemSessionStore and an application implementation of SessionLockInterface based on PHP’s flock():
use ExecKernel\Infrastructure\Engine\ExecKernelFactory;use ExecKernel\SessionStore\FilesystemSessionStore;use ExecKernel\SessionStore\HashStateVersioning;use ExecKernel\SessionStore\LockingSessionStore;
$backing = new FilesystemSessionStore($stateDirectory);$store = new LockingSessionStore( $backing, new RevisionsFileLock($lockDirectory),);$engine = (new ExecKernelFactory())->build( stateVersioning: new HashStateVersioning($backing),);RevisionsFileLock is application example code, available in the download below. All processes that write these sessions must use the same state directory and the same lock directory, with the same locking protocol. The directories belong to your application and must be writable by those processes. This example covers cooperating processes on one host; it does not supply a distributed lock.
A NullSessionLock provides no exclusion, and LockingSessionStore rejects guarded writes with that lock. A custom lock must actually protect every competing writer: the wrapper cannot make an unrelated writer cooperate. In particular, do not bypass it by writing directly to $backing.
The factory also accepts a sessionLock for engine operations. That lock ends before choose() returns to your application, so it does not cover a later application save. The store’s lock protects the persistence boundary shown here.
Keep the original token until the save
Section titled “Keep the original token until the save”For an existing session, obtain the token from the state you loaded. Keep that token alongside the candidate; do not replace it with a hash of the candidate:
$before = $store->load($sessionId) ?? throw new RuntimeException('Session missing.');$expectedHash = $store->getStateHash($before);
$result = $engine->choose( $graph, $before, $edgeId, $lang, sessionId: $sessionId, expectedStateHash: $expectedHash, deferEvents: true,);Here $graph is the definition for the saved session, and $edgeId is the choice the application received. The result contains a candidate state. The saved state remains unchanged until your application commits it.
The event batch is held in memory so that listeners do not receive this candidate as a confirmed application result. This uses the deferred publication described in Runtime events and listeners.
try { $saved = $store->saveWithExpectedHash( $sessionId, $result->state, $expectedHash, ); if (!$saved->persisted) { throw new RuntimeException('The choice was not saved.'); }} catch (Throwable $error) { $result->eventBatch?->discard(); throw $error;}
$result->eventBatch?->publish();For a new session, use createIfAbsent() so a colliding session ID cannot replace an existing session. Passing null to saveWithExpectedHash() retains the unconditional-save behavior; it is not a request to create only when absent.
If the write is confirmed but releasing the lock cannot be confirmed, LockingSessionStore returns the warning lock_release_unconfirmed and fences later mutations of that session through that wrapper. The saved result has not been rolled back. Inspect the warning and reconcile the lock’s ownership before continuing writes; reading remains available.
Respond to the conflict with the current session
Section titled “Respond to the conflict with the current session”A stale conditional write raises SessionPersistenceConflictException, with code EK-STATE-007. Discard that candidate’s event batch and load the session again. Your application can show the current result with a message such as “This session changed in another request.”
Do not automatically apply the old choice to the new state. That edge may no longer be available, or the user’s intention may need to be confirmed again. The same applies to external work: calculating a candidate should not mean an irreversible business action has already been performed.
The complete two-request example uses this application lock and the existing learning-path definition. Place those three files in your project’s root, alongside vendor/. The script uses an isolated temporary directory and removes it when finished. Its observable result is:
{ "same_initial_hash": true, "candidate_nodes": [20, 30], "first_write_persisted": true, "second_write_error": "EK-STATE-007", "reloaded_node": 20, "reloaded_history": [101], "published_transitions": 1}Both engine calculations succeeded before either save. The second commit still failed, which is the gap the conditional write closes.
The independent API uses a store generation
Section titled “The independent API uses a store generation”The independent API has its own ConditionalSessionStoreInterface, working with SessionSnapshot objects. Its saveIfUnchanged($expected, $candidate) compares the expected snapshot and its opaque writeVersion. The built-in in-memory and SQLite stores issue a fresh generation for every confirmed write, even if the state content is identical.
ExecKernelSessionService uses that capability for session creation and advancement. In the SQLite adapter, BEGIN IMMEDIATE protects the comparison and write across connections, and confirmation follows the commit. The in-memory adapter’s scope is its own process. A legacy custom store that only supports save and readback does not acquire CAS semantics through that compatibility path.
| Value | Meaning | Where it is used |
|---|---|---|
| Core state hash | Identifies the exact state value expected by an operation or write. | Core version precondition and conditional store. |
API writeVersion |
Identifies a particular confirmed store generation. | API store contract; it is not a public HTTP field. |
graph_version |
Identifies the graph revision used to interpret the session. | Graph identity and versioning. |
| Session HMAC | Verifies state integrity using a secret key. | State serialization and integrity. |
Use each value for its own decision. A graph revision or a valid signature does not establish that no other request has advanced the session.