Skip to content

Session expiration, history and retention

A session can stop accepting progress while remaining in storage. It can also disappear from a store without the engine evaluating another operation on it. To decide what a person will see when returning to your application, separate three policies: when execution expires, when its data is deleted and how much history the state retains.

History is the sequence of visited node IDs and traversed edge IDs. It belongs to SessionState and helps interpret the session’s path. Data retention is your application’s decision about how long to keep that state or the evidence it has recorded.

Mechanism What it decides What your application can observe
Engine expiration Whether the session remains active at the time of an operation. State may still load, but choose() or resume() rejects its use.
Store TTL or deletion Whether the record remains available to retrieve. load() may return null; the engine no longer receives that state.
History policy Whether more IDs may be appended while retaining earlier ones. The next transition can be rejected by the limit even if the session has not expired.

SessionExpirationPolicy lets you combine three limits. The engine checks them using the operation time and the state’s timestamps:

Parameter Measured from Expires when
ttl createdAt, the session start. Total age reaches this number of seconds.
idleTtl updatedAt, the last activity reflected in the state. Idle time reaches this number of seconds.
hardExpiration An absolute deadline expressed as a Unix timestamp. That instant is reached, regardless of age.

For example, your application can allow one hour of total lifetime, fifteen minutes without progressing, and a deadline belonging to the process itself. In this fragment, $deadlineTimestamp is that deadline calculated by your application:

use ExecKernel\Domain\Session\SessionExpirationPolicy;
use ExecKernel\Infrastructure\Engine\ExecKernelFactory;
$engine = (new ExecKernelFactory())->build(
sessionExpirationPolicy: new SessionExpirationPolicy(
ttl: 3600,
idleTtl: 900,
hardExpiration: $deadlineTimestamp,
),
);

A null value leaves that limit unset. Building the engine through ExecKernelFactory without expiration options does not enable a session TTL. The simpler sessionTtlSeconds parameter configures total age alone; if you supply a SessionExpirationPolicy, that policy takes precedence.

The exact deadline is already expired. If several limits coincide, the reason follows this order: hard_deadline, ttl, idle_timeout. A zero TTL expires immediately; use it only if you intend to prevent the session from starting active.

The engine checks the policy when operating on the session. It does not need a periodic job to mark a record as expired first. A completed choice updates the activity timestamps; querying a payload, resuming the screen or encountering a rejection does not renew the deadline. Total lifetime still runs from the start, even after progress. Your application must supply a coherent clock: an operation earlier than updatedAt is rejected instead of moving activity backwards.

Distinguish an expired session from a missing one

Section titled “Distinguish an expired session from a missing one”

To show the result, we reuse the graph from Anatomy of a graph: node 10 offers a guide through 101 and practice through 102, enabled by practiceEnabled: true. We will save this choice state with an engine TTL of 300 seconds.

Here, time is passed explicitly so that the boundary is visible; in a normal application, the engine’s time provider supplies the current instant:

$engine = (new ExecKernelFactory())->build(
sessionExpirationPolicy: new SessionExpirationPolicy(ttl: 300),
);
$startedAt = 1700000000;
$state = $engine->start(
$graph,
'en',
new \ExecKernel\Domain\Session\Context(['practiceEnabled' => true]),
timestamp: $startedAt,
)->state;
$store->save('learning-session', $state);

$graph is the loaded graph and $store is a core store, such as those configured in Session stores. Operating on that same state gives these results:

Action Time since start Result
resume() 299 seconds Returns node 10 and the same state.
getPayload() at the choice node 300 seconds Returns both options disabled, with disabled_reason: session_expired.
choose() or resume() 300 seconds Throws SessionExpiredException: EK-TIME-002, reason ttl.
$store->load('learning-session') After rejection Still returns the saved state if nobody has deleted it.
load() after delete() After deletion Returns null.

Querying the choice node lets your interface explain why options are no longer available. A terminal has no options to disable: if it has expired, getPayload() also rejects returning its outputs.

Your application can handle a resume rejection as an interface decision: explain that the deadline has passed and offer a new start where appropriate. Rejection does not replace or delete the previous state. You can still inspect it if your retention policy allows that.

Configure the API store’s TTL separately

Section titled “Configure the API store’s TTL separately”

The API memory and SQLite stores accept ttlSeconds. This TTL is measured from the state’s activity: the greater of updatedAt and lastTransitionAt. It must be a positive integer, or null to leave it unlimited.

For example, in an API integration with its snapshot already created:

use ExecKernelApi\Infrastructure\Session\InMemorySessionStore;
$store = new InMemorySessionStore(ttlSeconds: 300);

The store checks TTL when loading and writing. A load that finds an expired record deletes it and returns null; this is not a scheduled sweep of all records. An already expired candidate cannot be saved to renew the session artificially.

Its boundary differs from the engine policy: the store considers a record expired when elapsed time exceeds the TTL. If activity occurred at the starting second, with ttlSeconds: 300 a load still returns the snapshot at 300 seconds and deletes it at 301. With an engine TTL of 300, an operation is already rejected at 300. These are separate mechanisms configured in different components.

Reading the record does not update its activity timestamps. A session that nobody loads again may also remain physically stored after expiry. If your application needs deletion at a particular time, it must organize cleanup according to its storage policy. If it needs evidence of the process, it must record that before deleting state; State export and historical evidence explains what each artifact can provide.

The engine can use earlier visits and edges to evaluate rules and protect navigation. Removing that past changes the information used to interpret the session. Current policies therefore allow history to be retained or reject an append that would exceed the limit.

Policy Behavior
HistoryOverflowPolicy::PRESERVE Retains IDs even beyond the built-in limit of 256 items per list. This is the initial policy of an engine built with default configuration.
HistoryOverflowPolicy::REJECT Rejects an append if either the node list or the edge list would exceed 256. Retains the previous history.
HistoryOverflowPolicy::TRUNCATE A legacy marker. Configuring it for new history normalizes it to PRESERVE; it does not enable truncation.

To make new sessions reject overflow:

use ExecKernel\Domain\Session\HistoryOverflowPolicy;
$engine = (new ExecKernelFactory())->build(
historyOverflowPolicy: HistoryOverflowPolicy::REJECT,
);

The policy belongs to the history created for that session. When recovering an existing session, its serialized history policy applies; changing the configuration for future starts does not rewrite saved histories.

The following fragment isolates the collection limit. The numbers represent example entries, not a recorded navigation path:

use ExecKernel\Domain\Engine\PerformanceBudget;
use ExecKernel\Domain\Session\History;
$history = new History(
nodes: range(1, PerformanceBudget::HISTORY_MAX_LENGTH),
overflowPolicy: HistoryOverflowPolicy::REJECT,
);
$nextHistory = $history->withNode(257);

The last call throws HistoryLimitExceededException, code EK-PERF-004: it attempted to keep 257 entries when 256 are allowed. $history retains its 256 entries. During an engine operation, your application must handle this rejection without confirming progress that never completed. You can choose PRESERVE when longer paths are needed, accepting the resulting state growth.

When recovering old data, history marked truncate that reaches the historical limit is rejected because it may already have lost visits. A non-saturated legacy history retains its marker on read and changes to preserve when extended. That read compatibility does not make truncation a current policy.

lifecycle-policies.php shows the 300-second boundary, state still stored after expiry, explicit deletion and rejection of the 257th history entry. 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 example includes the outcomes shown on this page and uses explicit time so that waiting in real time is not part of the check.