State serialization and integrity
Saving a session requires a representation that can reconstruct it without changing its meaning. A number, context value or lost visit can affect a later engine decision. Your application therefore needs to retain the complete state and recover its types and values faithfully.
It may also need to check that nobody without its signing secret has modified that state. Serialization and this check address different needs: the first recovers valid data; the second adds a seal that detects alterations.
Represent the complete state
Section titled “Represent the complete state”SessionStatePersistenceSerializer converts a SessionState into an array suitable for persistence, encodes it as JSON and reconstructs it. It checks that the representation preserves the state and rejects incomplete data or values that cannot be recovered faithfully.
To see what it keeps, we reuse the graph from Anatomy of a graph. Its node 10 offers a guide and practice; practiceEnabled enables the latter. The following state remains at that choice. We add quantity and ratio as context values to show that integer 1 and decimal 1.0 retain their types.
{ "graph_code": "learning-path", "flow_id": null, "current_node": 10, "context": { "practiceEnabled": true, "quantity": 1, "ratio": 1.0 }, "history": { "edges": [], "nodes": [10], "overflow_policy": "preserve" }, "created_at": 1700000000, "updated_at": 1700000000, "last_transition_at": 1700000000, "graph_version": null, "dsl_version": null, "engine_version": null, "time_snapshot": null}Each group has a purpose when recovering the session:
| Part | What it recovers |
|---|---|
graph_code, graph_version, dsl_version |
The identity and versions the session expects. This example graph declares no versions. |
current_node and context |
The position and data used for further evaluation. |
history |
Earlier visits and choices, together with the policy governing growth. |
| The three timestamps | Start, activity and last transition, used by temporal checks. |
flow_id |
An optional adapter correlation; graph_code supplies graph identity. |
engine_version and time_snapshot |
Optional representation metadata. They remain null when not supplied to the serializer. |
The graph definition is kept separately. Your application also manages the session key used to look up this state in a store.
Serialize and reconstruct without changing data
Section titled “Serialize and reconstruct without changing data”Given $state returned by the engine, the round trip has four operations:
use ExecKernel\SessionStore\SessionStatePersistenceSerializer;
$codec = new SessionStatePersistenceSerializer();
$representation = $codec->serialize($state);$json = $codec->encode($representation);
// When reading the same bytes later:$decoded = $codec->decode($json);$restored = $codec->deserialize($decoded);serialize() prepares and validates the representation. encode() creates JSON while preserving values such as decimal 1.0. decode() checks the JSON structure before interpreting it; deserialize() reconstructs the domain objects and applies their validation.
For the example state, $restored->toArray() === $state->toArray() is true, and ratio remains a float. This fidelity matters because some rules compare values strictly. Reordering arrays, converting types or filling absent fields with assumed values can change what the engine evaluates.
The serializer rejects cases such as history without its lists, invalid timestamps, numbers that cannot be represented without loss, and JSON with duplicate keys. Your application should treat rejection as a recovery problem and retain the original record for diagnosis. Silently creating new state would hide the fact that the saved session could not be restored.
The built-in memory and file stores already use this serializer. Use it directly when your application implements its own representation or store. After reconstruction, the engine still checks that state belongs to the supplied graph and requested operation.
Choose the check you need
Section titled “Choose the check you need”State can be well formed and still have been altered. For example, changing practiceEnabled from true to false remains valid context. To distinguish equality, authenticity using a shared secret and confidentiality, use the appropriate mechanism:
| Mechanism | Question it answers | Scope |
|---|---|---|
HashStateVersioning |
Is this the same state that was read earlier? | Produces a comparison hash. It acts as a precondition alongside a conditional write; someone able to alter data can also recalculate a hash without a secret. |
HmacSessionIntegrity |
Does the state match the seal calculated using our secret? | Calculates and verifies an HMAC. The session-bound variant also includes the identifier. |
| Encryption managed by your application or storage | Can someone without the decryption key read the data? | Protects confidentiality according to the chosen system. An HMAC signature does not encrypt JSON. |
The concurrency page develops the precondition and conditional save. Here we use an HMAC seal, also called a signature in core interfaces: a digest calculated with a shared secret. Verifying it detects changes that were not accompanied by a valid seal.
Bind the signature to the session identifier
Section titled “Bind the signature to the session identifier”SignedSessionStore combines a state store, a signature store and a verifier. On save, it calculates the seal for the identifier and state. On load, it retrieves both and verifies that they still match.
In this fragment, $sessionSigningKey is a nonempty secret supplied by your application’s configuration. It must remain available when you verify the signed sessions again:
use ExecKernel\Infrastructure\Security\HmacSessionIntegrity;use ExecKernel\Infrastructure\SessionStore\InMemorySessionStore;use ExecKernel\SessionStore\InMemorySessionSignatureStore;use ExecKernel\SessionStore\SignedSessionStore;
$integrity = new HmacSessionIntegrity($sessionSigningKey);$states = new InMemorySessionStore();$seals = new InMemorySessionSignatureStore();
$signed = new SignedSessionStore($states, $seals, $integrity);$saved = $signed->save('learning-session', $restored);$verified = $signed->load('learning-session');Both example stores are in memory and demonstrate the mechanism within one process. To recover after a restart, your application needs persistent storage for both state and seal. The core provides SessionSignatureStoreInterface so you can supply that second store; the built-in signature store used here keeps signatures in memory.
The session-bound seal includes the exact key learning-session. Copying the same state and seal under another identifier does not verify. SignedSessionStore requires this session-bound contract, expressed by SessionBoundIntegrityInterface.
The HMAC covers the representation from SessionState::toArray() and, with the session-bound variant, the identifier. Additional metadata your application attaches outside state needs its own protection if used to make decisions. The sign($state) variant signs only the snapshot; it is not interchangeable with signForSession($id, $state).
Observe an alteration
Section titled “Observe an alteration”To simulate a change without a new seal, the complete example writes directly to the inner store:
use ExecKernel\Domain\Session\Context;
$changed = $restored->withContext(new Context([ ...$restored->context->toArray(), 'practiceEnabled' => false,]));
$states->save('learning-session', $changed);$verified = $signed->load('learning-session');The last call throws SessionIntegrityException, code EK-SEC-SES-001, reason signature_invalid. The structure remains valid, but state no longer matches its seal. Your application can reject recovery and record the identifier and reason without exposing the secret.
In normal use, your application saves through $signed so that state and signature are updated according to the contract. Direct access to the inner store in this fragment only represents the alteration we want to detect.
Preserve the meaning of partial confirmation
Section titled “Preserve the meaning of partial confirmation”The wrapper first saves state and waits for confirmation. It then saves the signature and checks its readback. It returns normal confirmation only when both parts have been confirmed.
If signature persistence fails after state is confirmed, SessionIntegrityException is thrown with reason signature_persist_failed and state_write_confirmed: true. State has already been written. Your application must retain that diagnosis and reconcile both records before accepting the session as correctly signed. The wrapper does not promise to revert state or authorize deleting it or repeating the entire operation without checking what happened.
Writer coordination must cover the complete pair too. When using conditional persistence with this wrapper, the cooperating lock goes around SignedSessionStore. Locking only the state store would leave the signature write outside that coordination. Concurrency and session revisions explains the scope your application’s lock needs.
Complete example
Section titled “Complete example”integrity-roundtrip.php creates state, shows its representation, verifies equality after recovery and detects an alteration. It uses the learning-path.json graph. Place both in your project root, alongside vendor/; the program loads vendor/autoload.php from that root.
The program generates an ephemeral key for the single-process demonstration and does not print it. In your application, inject the secret needed to verify retained sessions. For an inspection view or evidence of what happened, continue with State export and historical evidence: a recoverable state representation does not itself contain every historical observation.