Session state and serialization contracts
SessionState describes where a session is in a graph, the context used to evaluate its choices, and the path already taken. A store adds the identity and persistence information needed to retrieve that state. The independent HTTP API wraps it in its own SessionSnapshot.
These representations answer different questions. Use the domain fields to inspect execution state, the store contract to save or reconstruct it, and the API snapshot to understand server-side concurrency. A client SDK snapshot is a separate client representation; importing it does not restore a server backup.
Identify the representation
Section titled “Identify the representation”| Representation | Contains | Reconstruction or use |
|---|---|---|
SessionState::toArray() |
Graph identity, current node, context, history and timestamps | SessionState::fromArray() reconstructs a domain object. There is no session lookup ID in this array. |
SessionStatePersistenceSerializer::serialize() |
Domain fields plus engine_version and time_snapshot |
Normalizes a persistable representation and checks an exact domain round trip. |
| Core filesystem document | Serialized state plus session_id |
The filesystem store checks the embedded identity against the requested lookup ID. |
| Core in-memory entry | Serialized state under an application-supplied lookup key | The key identifies the session; save() does not add a session_id field to its value. |
ExecKernelApi\Application\Session\SessionSnapshot |
sessionId, state, lang and optional writeVersion |
Server-side API object passed to the API’s store port. |
| API SQL record | State JSON, duplicated query fields, language, write token and optional signature | The API validates the record and reconstructs its snapshot. |
| SDK snapshot | Client session representation | See the PHP SDK and JavaScript SDK references for their own fields. |
A state export or debug trace has a different format. Neither is the core store envelope described here.
Domain fields
Section titled “Domain fields”Every field below is emitted by SessionState::toArray(). The presence column describes SessionState::fromArray(); the persistence serializer imposes the additional requirements in the following section.
| Field | PHP value | Presence and meaning |
|---|---|---|
graph_code |
string |
Required, nonblank. Canonical graph identity. |
flow_id |
?int |
Optional; defaults to null. Legacy numeric graph identity. Numeric strings are rejected. |
current_node |
int |
Required. ID of the current node. Node existence is checked when the state is used with a graph. |
context |
array |
Defaults to [] when absent or null. Reconstructed through Context::fromArray() with the supplied policy. |
history |
array |
Defaults to [] when absent or null. Reconstructed through History::fromArray(). |
created_at |
int |
Required Unix timestamp in seconds. Session creation time. |
updated_at |
int |
Required Unix timestamp in seconds. Latest recorded state update. |
last_transition_at |
int |
Required Unix timestamp in seconds. Latest transition time. |
graph_version |
?string |
Optional; defaults to null. Graph revision attached to the state. |
dsl_version |
?string |
Optional; defaults to null. DSL/model version attached to the state. |
The ordering invariant is created_at <= last_transition_at <= updated_at. The state constructor does not impose a positive-ID or positive-timestamp rule. Reconstruction requires actual integer values for IDs and timestamps; it does not coerce numeric strings.
assertGraphCode(string $graphCode): void requires exact graph-code equality. assertGraphRevision(Graph $graph): void additionally requires exact graph_version and dsl_version equality, including null. A snapshot of an old revision is not silently rebound to the latest graph.
Here is a domain state after edge 101 moved a session from node 10 to node 20. The application’s reviewed flag is part of the context.
{ "graph_code": "state-contract", "flow_id": 7, "current_node": 20, "context": {"reviewed": true}, "history": { "edges": [101], "nodes": [10, 20], "overflow_policy": "preserve" }, "created_at": 1767225600, "updated_at": 1767225601, "last_transition_at": 1767225601, "graph_version": "1.0.0", "dsl_version": "1.0"}Download session-state-domain.json. Its domain round trip preserves the types and values shown above.
Context
Section titled “Context”Top-level keys must be strings accepted by ContextValidationPolicy. The default policy allows UTF-8 strings, integers, finite floats and booleans as values. It rejects null, objects, resources and arrays. Arrays require allowArrays: true and remain subject to the depth and value checks.
The reserved top-level keys are _execkernel, _history, _integrity and _session_age. A configured whitelist or regular expression can further restrict keys. See configuration, defaults and limits for the context and history budgets.
History
Section titled “History”| Field | Contract |
|---|---|
edges |
Traversed integer edge IDs in retained order; defaults to [] in History::fromArray(). |
nodes |
Visited integer node IDs in retained order; defaults to [] in History::fromArray(). |
overflow_policy |
preserve, reject or the legacy truncate value. Missing or null becomes reject during reconstruction. |
new History() defaults to preserve, whereas History::fromArray() without a policy defaults to reject. reject throws when either history collection exceeds the configured budget. preserve retains the complete collection.
Legacy truncate data at or above the historical limit is rejected because previous loss cannot be ruled out. A shorter legacy history can be read with its marker; subsequent changes use preservation rather than truncating new history. The persistence serializer also requires both history collections to be lists. History data alone does not provide the context updates and condition outcomes needed for historical replay.
Persistence serializer
Section titled “Persistence serializer”ExecKernel\SessionStore\SessionStatePersistenceSerializer exposes these operations:
| Signature | Result and checks |
|---|---|
serialize(SessionState $state, ?string $graphCode = null, ?string $engineVersion = null, ?array $timeSnapshot = null): array |
Optionally checks graph identity, adds engine_version and time_snapshot, normalizes, reconstructs the domain object and verifies exact equality with its original array. |
deserialize(array $payload, ?ContextValidationPolicy $contextPolicy = null, ?SessionIntegrityInterface $integrity = null, ?string $signature = null): SessionState |
Normalizes the payload and reconstructs state. An explicit context policy overrides the serializer’s configured policy. |
normalize(array $payload): array |
Requires context and history arrays, and explicit history.edges and history.nodes lists. Copies declarative data and normalizes the three timestamps. |
encode(array $payload): string |
Encodes JSON with JSON_PRESERVE_ZERO_FRACTION and checks exact encode/decode equality. |
decode(string $json): array |
Requires a JSON object; rejects malformed JSON, duplicate keys and integer overflow. It does not by itself reconstruct or normalize a session. |
assertSessionId(array $payload, string $sessionId): void |
If session_id is present, requires strict equality with the lookup ID. |
Unlike direct domain reconstruction, normalize() accepts timestamp strings that DateTimeEvaluator can parse as absolute dates and converts them to integer seconds. Use explicit timezone offsets when exchanging date strings. engine_version and time_snapshot are persistence metadata; they are not domain fields and deserialize() does not restore them into SessionState or use them as a compatibility check.
The filesystem envelope example contains the same domain state plus:
{ "engine_version": null, "time_snapshot": null, "session_id": "state-session"}This block shows only the additional fields. The complete download is a single object with both domain and store fields. The filesystem store chooses its filename from the SHA-256 of the session lookup ID, then checks the document’s identity on load. The domain state itself still has no sessionId property.
Core store and conditional writes
Section titled “Core store and conditional writes”| Core port | Signature |
|---|---|
SessionStoreInterface |
save(string $sessionId, SessionState $state): SessionPersistenceResult |
load(string $sessionId): ?SessionState |
|
delete(string $sessionId): void |
|
ConditionalSessionStoreInterface |
supportsConditionalWrites(): bool |
getStateHash(SessionState $state): string |
|
saveWithExpectedHash(string $sessionId, SessionState $state, ?string $expectedHash): SessionPersistenceResult |
|
createIfAbsent(string $sessionId, SessionState $state): SessionPersistenceResult |
SessionPersistenceResult contains state: SessionState, persisted: bool, stateHash: ?string and warnings: array. A successful calculation and a confirmed save are different outcomes: inspect persisted. The ordinary filesystem and in-memory stores return a persisted result with no state hash.
A state hash is an opaque concurrency value produced by the configured versioning/store implementation. It is not a field of SessionState, a graph version, or an authenticity signature. Base SessionStoreInterface implementations do not promise conditional writes merely because a hash has been calculated. Concurrency and revisions explains the supported composition and failure handling.
Integrity contracts
Section titled “Integrity contracts”| Interface | Methods | Meaning |
|---|---|---|
SessionIntegrityInterface |
sign(SessionState $state): string; verify(SessionState $state, string $signature): bool |
Authenticates a state snapshot. |
SessionBoundIntegrityInterface |
Adds signForSession(string $sessionId, SessionState $state): string and verifyForSession(string $sessionId, SessionState $state, string $signature): bool |
Authenticates both the state and the session lookup identity. |
HmacSessionIntegritySigner uses HMAC SHA-256 with separate domains for snapshot and session-bound signatures. Infrastructure\Security\HmacSessionIntegrity delegates to that implementation. A session-bound signature cannot be moved to another session ID, and a snapshot signature does not substitute for it.
When an integrity verifier is supplied to SessionState::fromArray() or deserialize(), the signature can come from the explicit argument or from integrity/signature in the payload. Every supplied value must be the same nonempty string. Missing, conflicting or invalid signatures raise SessionIntegrityException. Without a verifier, reconstruction does not authenticate these fields.
SignedSessionStore requires session-bound integrity and a separate signature store. It checks signatures during load and confirms that a signature was stored after a state write. A signature-storage failure can therefore report that the state write already succeeded. It rejects wrapping an inner store that already advertises conditional writes; conditional persistence belongs outside this decorator. See serialization and integrity for that composition.
Independent API snapshot and SQL record
Section titled “Independent API snapshot and SQL record”The API’s PHP object has this constructor:
use ExecKernelApi\Application\Session\SessionSnapshot;
new SessionSnapshot( sessionId: $sessionId, state: $state, lang: $lang, writeVersion: null,);Here $state is a domain SessionState. writeVersion is an optional API store token. sameContent() compares the session ID, language and encoded domain state; it does not compare the write token. withWriteVersion(string $version): self returns a snapshot carrying a token.
| API store operation | Contract |
|---|---|
save(SessionSnapshot $snapshot): void |
Ordinary write; different return type and argument list from the core port. |
load(string $sessionId): ?SessionSnapshot |
Returns an API snapshot, including language and persisted write token. |
delete(string $sessionId): void |
Removes the API session. |
createIfAbsent(SessionSnapshot $snapshot): SessionSnapshot |
Conditional creation; returns the stored snapshot. |
saveIfUnchanged(SessionSnapshot $expected, SessionSnapshot $snapshot): SessionSnapshot |
Requires the expected identity, token and content to match the stored snapshot; returns the new stored snapshot. |
The API’s PDO implementation requires SQLite. Its row fields are session_id, flow_id, current_node_id, payload_json, lang, created_at, updated_at, last_transition_at, write_version and signature. payload_json contains the persistence envelope, including session_id. The duplicated numeric and time columns must agree with the decoded state.
The generated write_version is 32 lowercase hexadecimal characters and changes on each confirmed write. It belongs to this API persistence protocol. If a row has a signature, a configured verifier is required; when integrity is enabled, a missing or invalid session-bound signature is rejected. Unreadable records are errors, not absent sessions.
For the API’s public response envelope, use HTTP endpoints and payloads. It is not the SQL record or the server-side SessionSnapshot object.