A bot conversation as a state machine: pause, cancellation, and return
Preserve an unfinished choice, distinguish pausing from cancellation, reject an outdated intent, and continue a conversation after the handler restarts.
A person chose a newsletter topic but did not finish selecting its frequency. They return to the bot later, after the application process has restarted. If the step existed only in the handler's memory, the bot asks for the topic again. If it tries to reconstruct the decision from the last text message, an incidental reply may become a new command. A clear continuation requires persisted state with defined transitions.
Consider a teaching example in Symfony Demo: a reader subscribes to astronomy or plants and chooses a weekly or monthly frequency. All identities are synthetic. Confirmation creates only a MySQL 8.4/InnoDB record through native PDO; the example sends no real email or Telegram message. We want to preserve an unfinished choice, return to the right question, and avoid reviving a cancelled conversation.
State describes the promise of the next step
Instead of an arbitrary step = 2, name what each state means. awaiting_topic means that no topic has been chosen yet. awaiting_frequency already has a topic and awaits a frequency. review contains both values and permits confirmation. paused temporarily stops editing. completed and cancelled end this particular conversation.
This is a finite state machine: a session has one state at a given moment, and a command can perform only an allowed transition. The Symfony Workflow documentation explains places, transitions, and the marking store. Our small model expresses the rules directly in PHP. The component can help organize a more complex graph, but choosing a library does not define what cancellation should mean.
| State | Data already present | Permitted meaning of the next action |
|---|---|---|
awaiting_topic |
No choice | Choose a topic, pause, or cancel |
awaiting_frequency |
Topic | Choose a frequency, pause, or cancel |
review |
Topic and frequency | Confirm, pause, or cancel |
paused |
Draft and previous active step | Resume or cancel |
completed |
Confirmed choice | A new conversation must be created separately |
cancelled |
Choice cleared | This conversation is no longer resumed |
The table defines this exercise's own policy. For example, editing an already selected topic from the review screen is not implemented here. If the product needs it, add an explicit transition and decide whether the frequency remains. Silently returning to the first step would leave that decision to chance.
A pause remembers the place; cancellation ends the draft
Recording only state = paused is insufficient for a pause. We need to know where to return. The resume_state field contains one of the three active steps. Topic and frequency remain in their existing fields. Resuming restores the previous state and clears resume_state, so the next pause begins from the current place.
If the reader stopped before choosing a frequency, returning should not require another question about the topic. If they stopped before confirmation, both values are shown again. Returning alone does not confirm a subscription. That still requires a separate command that the person deliberately submits at the current step.
Cancellation makes a different promise: the draft no longer exists as an unfinished request. The model moves it to cancelled and clears the topic, frequency, and return point. The resume command can no longer restore those values. The session record remains so that old events do not become the start of a new conversation.
A completed subscription is not cancelled by the draft-cancellation command either. After completed, a separate unsubscribe function with its own confirmation is needed. Otherwise, an old “Cancel” button referring to the choice process could remove an agreement that is already in effect. Button labels must correspond to a specific domain transition.
A session has its own identity and version
A conversation key should not be reduced to the last message or a username. The exercise has an opaque session ID bound to a bot, site, person, and chat. Context comes from a verified server adapter. A field in the command text cannot reassign the session to another reader.
That binding alone does not make an old command current. Every session change increments version; an intent contains the version against which the reader made their choice. A new event carrying an old value receives stale. The handler returns the current permitted state so the presentation can offer the current step, but does not apply an old choice to a new draft.
For example, choosing a topic changed the version to 1. A frequency command referring to version 0 no longer matches the displayed step. Rejecting it does not mean that the frequency is invalid in general. The presentation must be refreshed, and a new deliberate intent submitted with the current version and its own event key.
In this model, the version changes together with the persisted transition. A refusal caused by an invalid value does not increment it. That lets the reader correct a choice at the same step. A screen version, button expiry, and permission generation can be added separately if the product has corresponding rules; one counter must not silently mean all those things.
Replaying an event does not restore an old view
Delivery and application state have different identities. Telegram describes update_id in the Update contract; our local model scopes an event key to a particular bot. Identically named synthetic events from two bots therefore do not collide. At the same time, two different events with identical text are not automatically declared to be one intent.
A fingerprint of the context, session, expected version, and command is stored beside the key. A replay with the same fingerprint receives duplicate; replacing the content under an old key receives event_conflict. The receipt does not retain the full message text. A fingerprint of the bounded intent and a decision code are sufficient for this exercise.
A less obvious detail is that the receipt must not return an obsolete screen. Suppose the topic was selected successfully, and the reader later cancelled the session. Replaying the first event can confirm that the original transition once occurred. But the response must contain the current cancelled state without the previous draft values, rather than the old frequency-selection screen.
A replay result therefore carries two separate values: the previous decision code and the session's current state. Permission is checked before even that result is returned. The teaching model requires current permission for every command; a product may have different rules for viewing, cancelling, and confirming, which must be defined separately.
The transition and local result are stored together
Losing a process between storing state and creating the subscription is dangerous. If completed is saved while the subscription is created later, the next handler may wrongly conclude that the work is finished. Reversing the order without a shared boundary leaves another problem: the record exists, but the session still offers confirmation.
In the exercise, sessions, permissions, receipts, and subscriptions live in one MySQL 8.4 schema, in InnoDB tables with foreign keys and CHECK constraints. Using native PDO, the handler starts a transaction, reads the current context and permission, checks the replay and version, applies the transition, and saves the result. REPEATABLE READ isolation and InnoDB row locks apply here, rather than a database-wide single-writer limit. Lock-wait timeout 1205 and deadlock 1213 are not domain refusals: ConversationMachine::handle() catches storage exceptions and returns storage_unknown, rather than propagating native exceptions to the caller. Before returning, the handler attempts to roll back the transaction if it owns it and it is still active. Failure of that attempt is also caught; the outcome deliberately does not claim a confirmed commit or rollback. The InnoDB error-handling documentation explains the distinctions.
Before running commands, a separate migrator explicitly prepares the schema; the runtime account performs data operations only and has no CREATE, ALTER, or DROP privileges. Teaching checks use the guarded disposable MySQL fixture and App\Infrastructure\MysqlLab. DDL runs before the business transaction: MySQL can implicitly commit DDL, so this is neither an atomic schema upgrade nor an automatic transfer of data from the old SQLite database.
The update also includes the expected version. The following is a shortened form of the rule; draft fields are stored in the same operation:
UPDATE sessions
SET state = :next_state, version = version + 1
WHERE id = :session_id AND version = :expected_version;
Confirmation inserts one local subscription record, unique to the session. The event receipt is written in that same transaction. A successful response is returned only after a known commit. If storage returns an uncertain outcome, storage_unknown does not present it as a proven refusal; recovery uses the same event key.
This boundary applies to one database. It does not ensure a single send through Telegram or an email service. An external action needs separate accounting for attempts and their outcome. The handler does not take ownership of someone else's open transaction either: otherwise, its “done” could depend on another piece of code's later decision.
Check restarts with separate processes
A persisted row must survive the handler's termination. To check restarts, first explicitly prepare the disposable schema with the migrator, then run topic selection, pause, resume, frequency selection, confirmation, and replay of that confirmation in separate PHP processes. Each process must open its own native connection to the same MySQL schema, which remains available until the scenario finishes. The expected states are awaiting_frequency, paused, awaiting_frequency, review, completed, completed; versions are 1, 2, 3, 4, 5, 5; and subscription counts are 0, 0, 0, 0, 1, 1. This checks persisted data across processes, not a shared in-memory object or a SQLite file.
This is a stronger recovery check than constructing a new object in the same process. However, normal process termination does not simulate an abrupt power loss. A separate test using an exception before commit can check whether state, subscription, and receipt roll back together, allowing a replay with the same key to perform the transition.
This model's check matrix covers pausing at each active step, clearing after cancellation, terminal states, a foreign context, revoked permission, and a conflicting replay. Database checks run on actual MySQL 8.4: the fixture migrator prepares the schema, while runtime code and result assertions perform no DDL. The important invariants are that an old replay leaves a cancelled draft unchanged, each session has at most one subscription, and state, subscription, and receipt share a transaction boundary. A normal restart does not demonstrate resilience to a forced crash or power loss. Expiry, authentication, provider delivery, and behavior in a real client remain separate checks.
Conversation memory has defined contents and a lifetime
Persisting state does not mean retaining the entire correspondence. This exercise needs only a few choice values, the return point, a version, and receipts. Pausing creates no hidden subscription and starts no reminders. If such actions are needed, name them as separate transitions or effects with their own conditions.
Old-session cleanup is not implemented here. While replaying old events remains supported, indiscriminately deleting receipts weakens that contract. A real product must define the draft-resumption period, the replay-acceptance period, and behavior after both end. Automatically starting a new session from any old callback would be a different, far less predictable rule.
The useful outcome of this model appears in the answers to simple questions. Where did the person stop? What exactly was saved? Can they still return? Has the subscription already been created? When each question has an answer in the current state and its receipt, restarting the handler no longer means starting a new conversation.
The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.
Check the current example against an owned disposable MySQL schema:
bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/ConversationLab