Staying up: restarts, sessions and hosting
What an agent needs to be there tomorrow: keeping a conversation across restarts, announcing interrupted work instead of resuming it, refusing stale messages, restarting through a supervisor, and hosting with no inbound port, a pinned clock and data kept apart from code.
- Separate what an agent holds only while its process runs from what must be kept on disk, and say where each part of a conversation lives.
- Explain why a task interrupted by a restart is announced to the owner and not resumed, and what the announcement must contain.
- Handle messages that arrive while the program is down, without carrying out stale instructions.
- Restart a program after its configuration changes using a supervisor, and explain why restarting inside the same process is not enough.
- Describe a hosting arrangement with no inbound port, and say what changes when a service must call back to the program.
- Name the two things that are easy to get wrong when moving such a program to a server.
- Move a running assistant and its data from one machine to another without two copies ever answering, and say what must be checked from outside afterwards.
- Week
- 4 of 14
- Before it
- Chapter 4 and Chapter 6; Definitions 2, 3, 5 and 8 and Property 3 of the model.
- Read first
- [Candea and Fox 2003]; [Helland 2012].
- Laboratory
- 1: the loop, the journal and a conversation that can be stopped
- Problem set
- 2
7.1The problem: an assistant that is there tomorrow
At ten past four the owner asks their assistant to draft a reply to a supplier. The draft appears, and they go into a meeting. While they are out, the program is updated, which means it is stopped and started again. At five they write "Looks good, send it." A program that kept the conversation only in its running memory now answers "Send what?". Worse things are possible. If the update had come in the middle of the sending, the owner would have no way to tell whether the email had gone, and a program that simply carried on might send it twice.
Restarts happen often. Every update is one, every crash is one, and on a laptop every lid closed is a kind of one. An agent that acts on its owner's behalf has to survive them without losing its place, without doing anything twice, and without leaving the owner to guess. It also has to run somewhere that stays awake, because a reminder set for seven in the morning is worth nothing if the computer is asleep at seven.
7.2Where state lives
The first step is to sort everything the program knows into two piles: what vanishes when the process ends, and what is on disk.
- Process
- One running copy of the program. Everything held in its variables (open connections, a task in progress, a question waiting for an answer) ends when it ends.
- Session
- One conversation as the agent library sees it: the sequence of messages and tool results the model is shown.
- Transcript
- The agent library's own file of a session, from which the session can be picked up again.
- Resume
- Starting the agent with the identifier of an earlier session, so that it continues that conversation instead of beginning a new one.
| Thing | Where it lives | After a restart |
|---|---|---|
| Memory, the schedule, the journal (Chapter 4) | Files in the data folder | Kept |
| The conversation | A small file holding the session's identifier, and the library's transcript, both in the data folder | Resumed |
| The record of private details read from the owner's accounts, and of the kinds of outside material the conversation has read | A file of short hashes and a small list, both in the data folder | Kept, so the check on what leaves through a search still works |
| Sign-in tokens for connected services | Files in the data folder | Kept |
| A task in progress | The process | Lost; announced to the owner |
| Messages waiting behind that task | The process, with a copy of their first words in the journal | Lost; named in the announcement |
| An approval question on the owner's screen | The process | Dead, by design; the announcement says so |
Two rows deserve a comment. The record of private details is kept on disk because the conversation is. Were it held only in the process, a resumed conversation would still have the owner's mail in front of the model while the check that stops mail leaving through a search had forgotten everything. In general, once one piece of state outlives the process, every check that depends on it must outlive the process too. The second is the approval question. Chapter 8 explains that an approval covers exact inputs for one use and is held by the running program. Writing it to disk so that it could be honoured after a restart would let a tap made hours later approve something the owner can no longer see in context. So it is not kept.
7.3The design
The design answers five questions. For each, the obvious alternative and why it was not taken.
| Question | Choice | Obvious alternative, and why not |
|---|---|---|
| How does a conversation survive? | Keep the session identifier and the library's transcript in the data folder, and resume | Rebuild the conversation from Odysseus's own journal. The library already knows how to resume; it had simply never been told the identifier. |
| What happens to an interrupted task? | Announce it, with its first words, and do not carry it on | Resume it. The program cannot know how far it got, and an action done twice cannot be undone. |
| What happens to a message that arrives while the program is down? | If it is more than ten minutes old on arrival, report it and do not act | Act on it. An hours-old instruction may already have been done by hand. |
| How does the program restart itself? | Exit with a special code; a supervisor starts a fresh process | Restart inside the same process. Process-wide state, such as the tracing client, stayed shut. |
| How do messages reach a server? | The program asks Telegram for them (long polling); no port is open | A webhook, where Telegram calls the server. That needs a public address and a defended door. |
7.4Mechanism: a conversation that survives
The agent runner in odysseus/agent.py keeps the session's identifier in a file beside the rest of the data, and tells the agent library to write its transcript there too:
# The conversation outlives the program. Its id is kept in a small file beside the other data, and the agent
# library's own transcript is kept there too (CLAUDE_CONFIG_DIR below), so that on a server both are on the
# disk that survives an update. Before this, any restart began a new conversation without saying so.
self._session_file = settings.data_dir / "session.json"
self._transcripts = settings.data_dir / "agent"
self.session_id: str | None = self._load_session() if persist else None
The options passed to the library then include resume=self.session_id and an environment variable, CLAUDE_CONFIG_DIR, pointing at that agent folder. The second half is easy to miss. On a server, the library's usual place for transcripts is inside the image, and an update replaces the image. An identifier pointing to a transcript that no longer exists would be worse than no identifier. Keeping both on the disk that survives an update is what makes the identifier worth keeping.
The identifier is written after each task, when the library reports it, and deleted when the owner sends /new. A damaged file is read as "no conversation", not as an error. If the identifier is present but the session cannot be picked up, the runner starts a new one rather than failing every message from then on:
try:
await client.connect()
except Exception as e:
if self.session_id is None:
raise
# The saved conversation could not be picked up (its transcript is gone or unreadable).
# Start a new one rather than fail every message from now on.
self._journal.write("error", where="agent.resume", error=type(e).__name__, message=str(e)[:200])
self.lost_session = True
self.session_id, self._resumed, self._blank = None, False, True
self._save_session()
client = self._factory(options=self.options())
await client.connect()
Setting _blank matters: it tells the conversation that the model has no context, so the owner's memory is shown again with the next message (Chapter 5). The _resumed flag is used by the restart notice to say whether the earlier conversation was kept. lost_session is read by main after the client connects: when nothing was interrupted but the conversation could not be picked up, the owner is sent one line saying so (LOST_CONVERSATION in odysseus/__main__.py).
A conversation that never ends also grows without limit. The library condenses long conversations by itself, and the owner can send /new to start again on purpose. Memory, reminders and connections are untouched by /new; only the back-and-forth is dropped. Chapter 2 explains condensing, and Chapter 20 what a long thread costs.
7.5Mechanism: announce, do not resume
When the program starts, before it writes anything, it reads its own journal to find out what the last run left unfinished. The function is unfinished in odysseus/__main__.py:
for r in journal.read():
if r["kind"] == "start":
open_task, waiting, behind = None, {}, None # an earlier restart: whatever was lost then has been reported already
elif r["kind"] == "task_start" and r.get("background"):
behind = r.get("preview", "") # a job in the background has its own beginning and end
elif r["kind"] == "task_end" and r.get("background"):
behind = None
elif r["kind"] == "task_start":
open_task = {"preview": r.get("preview", ""), "asked": False}
elif r["kind"] == "task_end" and "routine" not in r and "brief" not in r:
open_task = None
elif r["kind"] == "queued" and "q" in r:
waiting[r["q"]] = r.get("preview", "")
elif r["kind"] == "dequeued":
waiting.pop(r.get("q"), None)
elif r["kind"] == "queue_cleared":
waiting = {}
elif r["kind"] == "gate" and r.get("verdict") == "asked" and open_task is not None:
open_task["asked"] = True
elif r["kind"] == "gate" and r.get("verdict") in ("approved", "declined", "expired", "cancelled", "unasked") and open_task is not None:
open_task["asked"] = False
This works because the conversation writes the right lines at the right moments. Each task begins with a task_start line carrying the first eighty characters of the request. Each message that has to wait behind a running task is written as queued with its own number and first words, and as dequeued when its turn comes. A start line marks each run of the program, so what was lost before an earlier restart is reported once, not at every later start. And the end of a routine or of a meeting brief is ignored (their task_end lines carry a routine or brief field), so work finishing elsewhere does not hide an interrupted conversation task. Only the conversation writes task_start; a job it runs in the background has its start and end marked background, and is reported separately. One line used to escape the rule: a lookup of whom to ask about a contact writes a task_end marked leads, which unfinished did not ignore, so a conversation task cut off after such a lookup was not reported. The marks of all such side work are now one list, and a test holds the case.
Without the journal lines written before the work, there is nothing to find. A log that records only completions cannot tell a task that never started from one that died halfway.
The program does not carry on, because it cannot know how far the task got. A tool call can succeed even though its reply never arrived: Chapter 18 calls this the lost acknowledgement. A restart is the same uncertainty at a larger scale. The email may have left in the last instant before the process stopped. Telling the owner costs one message; a duplicate email cannot be recalled.
The notice is sent to the owner before the start line is written. For the host's own assistant it is sent after the agent client has connected, so that the program knows whether the conversation was resumed. An invited person's agents connect only at their first message, so their notice assumes the saved conversation will be picked up.
7.6Worked example: a restart with work in flight
Input. The owner asks "Summarise my inbox". While that task runs, they send three more messages. The summary is sent, the first waiting message is taken up, and the process is stopped while it runs. The journal ends like this (fields trimmed):
{"kind": "task_start", "preview": "Summarise my inbox"}
{"kind": "queued", "q": 1, "preview": "Remind me to call the plumber at 5"}
{"kind": "queued", "q": 2, "preview": "What is on tomorrow?"}
{"kind": "queued", "q": 3, "preview": "Book the dentist"}
{"kind": "task_end", "status": "done"}
{"kind": "dequeued", "q": 1}
{"kind": "task_start", "preview": "Remind me to call the plumber at 5"}
What each part does. At start, unfinished walks the journal. The first task_start opens a task. The three queued lines add three waiting messages. The task_end closes the first task. The dequeued line removes the first waiting message, and the second task_start opens the task that was cut off. No task_end follows it, so it is still open. No gate line says a question was asked. The result is the summary {"preview": "Remind me to call the plumber at 5", "asked": False, "waiting": ["What is on tomorrow?", "Book the dentist"]}.
The runner connects and finds session.json, so it resumes. restart_notice then builds the text.
Output. The owner receives:
I was restarted while I was working on something: "Remind me to call the plumber at 5". It was not finished, and I have not carried on with it by myself. 2 messages you sent were waiting behind it and were lost: "What is on tomorrow?"; "Book the dentist". Ask me again if you still want these done.
Had a question been on the owner's screen, the notice would add that the question "no longer counts, so tapping it will do nothing", because a button that silently does nothing looks like a fault. Had the conversation not been resumed, it would end with "I also no longer have our earlier conversation, only what I remember about you." A test in tests/test_durability.py checks the same counting on a shortened journal.
7.7Messages that arrive while the program is down
Telegram holds messages for a bot that is not running and hands them over when it returns, for about a day; WhatsApp holds them for about a day and a half. That is convenient and dangerous. "Send the contract to the agent", written at nine and delivered at three, may have been done by hand in between, or may no longer be wanted.
So the Telegram wiring in odysseus/telegram.py checks the age of every message from the owner before passing it on:
user_id = message.from_user.id if message.from_user else 0
sent = message.date if message.date.tzinfo else message.date.replace(tzinfo=timezone.utc)
age = (datetime.now(timezone.utc) - sent).total_seconds()
if age <= STALE_AFTER_S or not conversation.is_owner(user_id):
return False
loop_time = asyncio.get_running_loop().time()
if loop_time - told_late[0] >= 60 or told_late[0] == 0.0:
told_late[0] = loop_time
await TelegramChat(bot, message.chat.id).send("Something you sent earlier has only just reached me, because I was not running at "
"the time. I have not acted on it. Send it again if you still want it.")
return True
STALE_AFTER_S is 600 seconds. A message older than that on arrival is reported and not run. The owner is told at most once a minute, so a backlog of twenty messages produces one notice, not twenty. The WhatsApp channel has the same rule (Chapter 16).
Two other kinds of thing arrive, or fail to, while the program is down. A reminder whose time passed is sent once on return, marked as late and saying why, and a repeating one moves to its next future time rather than firing once for each missed day (Chapter 6). Events from the owner's mail and calendar that a watch was waiting for are simply missed: nothing goes back for them.
7.8Restarting itself after a configuration change
Some changes need a restart. When the owner connects a new service from the chat (Chapter 13), the service brings new tools, and the set of tools is fixed when the agent client connects. The program has to start again to use them.
The obvious way is to restart inside the running process: stop polling, tear everything down, build it all again. That leaves behind anything that exists once per process and was shut by the first clean-up. A restart must begin from a new process.
Restarting in place worked every time it was tried, in testing and in the owner's real chat. Every trace after the first restart was nonetheless silently dropped. The tracing client exists once per process, the first run's clean-up had shut it, and nothing reopened it. The live check of tracing runs one task in a fresh process, so it could not see this. No test found it; running the errand for real, connect after connect, did.
What follows is how the restart was first made safe. It is no longer what happens on a new connection. Once each person's assistant was built by one function from one folder (Chapter 16), connecting a service could close that one assistant and build it again, leaving everything that exists once per process open: the tracing client, the bot, the other people. The supervisor remains, for whatever next needs a clean process.
- Supervisor
- A small parent process whose only job is to start the real program as a child and decide, when the child exits, whether to start another.
A new process has none of the old one's history. So python -m odysseus starts a supervisor, which runs the program as a child marked by an environment variable:
def supervise() -> int:
import os
import subprocess
env = {**os.environ, "ODYSSEUS_CHILD": "1"}
while True:
child = subprocess.Popen([sys.executable, "-W", "ignore", "-m", "odysseus"], env=env)
try:
code = child.wait()
except KeyboardInterrupt:
child.terminate()
return 130
if code != RESTART:
return code
The child asks for a restart by exiting with the code RESTART, which is 75. Inside main, the function handed to the connector records the request and stops the Telegram poller one and a half seconds later; the clean-up in main's finally block closes every client, and main returns 75. Any other exit code, including a crash, ends the supervisor with that code, and whatever runs the supervisor (a terminal, or a host's restart policy) decides what happens next. The restart re-uses the mechanism above: the new child resumes the session, and because /connect is refused while a task is running, there is no interrupted task to announce.
Verified, live, in the owner's real chat with real servers, with the in-process restart that came before the supervisor: nine connects and disconnects in a row each ended with the assistant back in about twenty seconds, and after the last it used the new service. It was this run that showed traces were being dropped. The supervisor itself is verified by a unit test in tests/test_startup.py; no live restart through it is recorded.
One restart failed because of a wrong argument in the code that assembles the program at start-up. No test had caught it, because every other test builds its pieces by hand and never runs main. tests/test_startup.py was added for that reason: it runs main with stand-ins for Telegram and the agent client, once with every optional service configured and once with none. More generally, the code that runs only at start is the code a restart depends on, and it needs a test of its own.
How long a start takes
Every restart is a stretch in which the assistant cannot answer, so how long a start takes is part of staying up. Nobody had measured it. On the laptop it took about a minute from launch to the first message it could answer, and felt longer when the machine was busy.
The cause was found by writing the time at each stage of start-up into the start line of the journal, where it now stays. Almost all of the minute was the loading of libraries, in two avoidable places. The supervisor, a process whose whole job is to start the child and wait, was loading every library the child uses before starting it, and the child then loaded them all again: thirteen seconds spent twice. And the second reader of outgoing mail (Chapter 8) loaded its own library while the program was starting, twelve seconds for something first needed minutes or hours later.
The supervisor now leaves before those libraries are reached, and the reader's library is loaded in the background once the program is already answering. A start measured after the change took 31 seconds. Verified, one start before and one after; the figures vary by several seconds with what else the machine is doing. What is left is the loading of three libraries the program cannot run without, and connecting the agent loop.
Start-up time stayed high for the reason given in Chapter 20 for money: nobody had written it down. The timing line cost four lines of code.
7.9A home that stays awake
A program with a scheduler cannot live on a laptop: it does its scheduled work only while the laptop is awake. The fix is a rented machine that does not sleep. A deployment of Odysseus consists of four things.
- Image
- A sealed package containing the program and everything it needs to run: the language version, the libraries, the code. The same image runs the same way anywhere.
- Machine
- A small rented computer that runs one image.
- Volume
- A disk attached to a machine that keeps its contents when the machine is replaced.
- Secret
- A value such as a key, stored encrypted by the hosting service and handed to the program as an environment variable when it starts, never written in the code or the image.
| Thing | What it holds | On an update |
|---|---|---|
| Image | The program and its libraries. No keys, no data, no tests, no website. | Rebuilt and replaced |
| Machine | One shared processor and one gigabyte of memory, always on, with swap on its own disk (the measurement that made the swap necessary is below) | Restarted on the new image |
| Volume | The data folder: memory, schedule, journal, session, transcripts, tokens | Untouched |
| Secrets | The keys for Telegram, the model and each optional service, and the owner's Telegram identifier | Untouched |
The right-hand column shows what an update touches. Code changes often and can be replaced, data must survive a change of code, and keys belong in neither. Because everything that must last is in one folder, the volume is mounted exactly there, and the image sets ODYSSEUS_DATA_DIR=/data.
No inbound port
Most programs on servers wait for connections from the internet, so they need an address and an open port, and must be defended against everyone who finds it. For its first channel Odysseus needs none.
- Long polling
- A way to receive messages by asking the service for them repeatedly; each request waits until there is something to return or a timeout passes. Every connection is started by the program.
- Webhook
- The reverse arrangement: the service calls an address the program publishes each time there is something new. The program must be reachable from the internet.
The Telegram bot uses long polling, and every other connection the program makes (to the model, search, the connector, the browser service) is outward too. With Telegram alone, nothing on the internet can start a conversation with the machine, because nothing is listening, and the hosting configuration can say so by having no section that describes a web service. The deployment described here does open one port, for the two reasons in the next section, and the comment at the head of fly.toml names both and says how to go back to none.
Long polling has one rule that matters: only one program may poll for a given bot at a time. Two copies take messages from each other. The copy on a laptop must be stopped before a server's copy starts, which creates the gap described below.
When a service must call back
Two features break the "no door" property, in different ways.
The first is a channel that only works by webhook. WhatsApp's business interface calls the program each time a message arrives, so switching it on opens one port. Chapter 16 covers what that changes and how the calls are checked.
The second is subtler: a sign-in that returns to the program. Services with their own server are connected by a sign-in exchange in which the owner approves in a browser and the service then sends that browser back to an address on the machine the program runs on, such as 127.0.0.1, carrying a one-time code. The program listens on that port and waits up to ten minutes for the code. On a laptop where the owner is also reading the chat, this works. On a server it does not: the owner's phone cannot reach 127.0.0.1 on a machine in a data centre. So on a server the program is told its own public address and the sign-in returns to a page there, behind the same one port (Chapter 16). Chapter 10 covers the exchange itself and the ports a program opens for it.
Both features sit behind one listener, odysseus/door.py. It answers four things and nothing else: the sign-in page, WhatsApp's address when that channel is on, /health, and "not found".
Secrets and data on a host
Keys go into the host's secret store, imported from the local .env file, which is ignored by version control, never copied into the image and never shown to the model. The image runs the program as an ordinary user rather than the administrator, which limits what a fault could damage.
The data folder is the sensitive part. Once the conversation is saved, mail text the model has read is on disk in the clear, in the transcripts. A data folder inside a folder that a file-syncing service copies to its own servers means another company holding the owner's mail, chosen by nobody; this happened on the owner's laptop, and moving the folder out did not recall the copies already taken. So the program warns at start-up if its data folder is inside a synced one, and every agent, including the unattended ones, writes its transcript inside the data folder and nowhere else. Nothing backs up the volume beyond whatever the host does by default.
7.10Moving a running assistant
The program had been in daily use on a laptop for some time before it was given a server, so the move was of a live assistant with a conversation, sign-ins, a schedule and a second person's folder. The order of the steps is the content of this section, because each step exists to prevent one particular fault.
- Build the server with the program held still. A deployment normally starts the program, and a started program polls Telegram. The server's disk also still held a folder from an earlier attempt. A program started on it would have been a second poller, announcing itself from data several days old. So the first deployment replaced the start command with one that sleeps, which gives a running machine with the disk mounted and no program.
- Rehearse the copy while the old copy still runs. The data folder was packed into one archive, sent, unpacked into a scratch folder on the server and counted. The count on the server equalled the count on the laptop. The rehearsal also found a fault in the script that was to do the real thing, which is what a rehearsal is for.
- Wait until nothing is in flight. The journal was read for a task that had started and not ended, for the owner and for the invited person. The move began after five minutes with neither.
- Stop the old copy, and check that it is gone. The whole tree of processes was ended and the machine's process list read again. The check counted two unrelated programs as survivors at first, because it matched on the folder's name. A check for "is the old one still running" has to name the program, not the place it lives.
- Copy again, for real. The archive was made a second time, now with nothing writing to the folder, and unpacked in place. What was already on the disk was moved into a folder of its own on the same disk and not deleted.
- Start the program. A second deployment with the real start command. From the old copy stopping to the new one writing its
startline took about six minutes, most of it the copy and a slip described below.
What the move found
The agent library keeps each conversation's transcript in a folder named after the directory the program was started in. On the laptop that name was built from a Windows path; on the server the program starts in /app. The session identifier travelled in session.json, and the transcript travelled too, into a folder the library on the server would never look in. Left alone, the first start would have failed to resume, begun a new conversation and said so. The transcript folders were renamed on the server to the name the library derives from /app, for the owner and for the invited person, and the first start recorded no failure to resume.
The first version of the renaming step renamed the folder and then tried to descend into it under its old name, failed, and stopped the script before the files had been handed to the program's user. It was put right by hand in a minute. The rehearsal had not covered this step, because the rehearsal unpacked and counted and went no further. Rehearse the whole script, not the part that looks risky.
After the first real start the host's dashboard showed the machine started and its health check passing. From anywhere else the address did not resolve. The application had been created at a time when it had no web service, so the host had never given it a public address, and adding the service later did not add one. The host's own check runs inside the host's network and passed all the while. Two commands allocated the addresses. A health check that passes says the program answers the host; whether the world can reach it has to be asked from the world.
This chapter listed "whether one gigabyte of memory is enough" as untested. Measured on the server with only the owner's agents connected: the program itself held about 390 MB and each of three connected agents about 130 MB, about 770 MB in all, and the machine reported 70 MB available. An invited person's first message connects more agents at about 130 MB each. The laptop figures in Chapter 16 were lower, and were measured on a different operating system; they did not transfer.
Two answers exist. Swap on the machine's own disk costs nothing and was switched on at once: running out of memory becomes running slowly, and the host's rule for a process that runs out is to kill it. A second gigabyte costs about as much again as the machine does and is the real answer for more than one person. Within minutes of the swap being switched on about 110 MB had been moved to it.
Four smaller findings.
- A token that must stay behind. The record of the owner's own activity (Chapter 13) is served from the laptop to programs on the laptop. Its token was left out of the archive on purpose: a hosted assistant carrying it would list a service it can never reach. That service stops being available to a hosted assistant. Making it available would mean the laptop publishing the owner's screen activity to an address on the internet, which is a decision of its own and was not taken.
- The copy left behind is now dangerous. A renewal token is good for one use (Chapter 10). The folder on the laptop still holds the renewal tokens as they were at the moment of the move. If the old copy were started again it would spend them, and the server's sign-ins to those services would die at their next renewal. A second poller is the fault everyone expects from running the old copy; this one is quieter. The old folder is kept as a backup and must not be run.
- A setting that must not travel. The laptop's settings file names its data folder by a Windows path. Imported with the other settings it would have overridden the server's own. Settings were imported by name, leaving that one out, along with a WhatsApp token that had expired.
- The host's rule had changed. The earlier deployment was stopped at five minutes under a rule for accounts with no payment card. The host's published terms no longer describe that rule. A finding about a vendor is a finding about a moment.
Knowing that it is up, and going back
| Sign | Proves | Does not prove |
|---|---|---|
The host's check of /health, every thirty seconds | The process is running and its event loop answers | That Telegram is being polled, that any key works, or that the address is reachable from outside |
/status in the chat | The whole path: Telegram, the program, a reply | Nothing while the owner is not looking |
The start line in the journal | When it last started, what was connected, and how long each stage took | Anything since |
| A scheduled message arriving | The schedule and the channel | Nothing until one is missed, and a missed message is easy not to notice |
None of these tells the owner when the program dies. The host restarts a process that exits, whatever its exit code, and a deployment is the same restart, which the interrupted-task notice above covers. What is still missing is the watcher from outside described under "What goes wrong".
Going back has two halves. The code goes back by deploying the previous image again, which the host keeps for a while and does not promise to keep. The data does not go back with it: the host photographs the disk once a day and keeps the photographs for a number of days set in the configuration, and restoring one means making a new disk from it. The disk lives on one physical machine, and the host's own documentation says a single disk should not be the only copy of anything. Nothing here copies the data folder anywhere else yet.
The host's machine went down, and nobody was told
The table above was tested by the failure it warns of. The physical machine the program runs on was taken out of service by the host for emergency maintenance. The program, its disk and its public address were unreachable for about twenty-nine hours. Every sign in the table went quiet together, and silence is the one thing none of them reports.
- It was found by accident. Eleven hours in, a deployment failed because it could not reach the machine. The owner had sent nothing in that time and had no reason to look.
- The host's public status page said everything was working for the whole of it. The notice was attached to the account's own machine and was read with the host's command-line tool. A status page describes the host, not a customer's one machine.
- Restart policies did nothing, because there was nothing to restart: the process had not exited, its machine had gone. A deployment could not move it either, since the disk lives on that machine and the program cannot start without it.
- The choice was to wait or to go back a day. A new machine could have been made from the latest photograph of the disk. That photograph was a day old and getting older, because none can be taken while the machine is unreachable. It would also have brought back renewal tokens that had since been used once and were therefore dead, so four connected services would each have needed signing in again; and the old machine would have had to be destroyed before it returned, or two copies would have polled the first channel. The owner chose to wait. The machine came back, the program restarted itself, and no data was lost.
- The photographs were kept for fewer days than the configuration said. The setting for how long to keep them applies when a disk is made. The disk had been made before the setting was written, and kept its original, shorter period.
What this argues for is what the chapter already lists as missing, in order of worth: a watcher outside the host that tells the owner on another channel when the address stops answering, which would have turned eleven unnoticed hours into minutes; and a second copy of the data somewhere other than that one machine, recent enough that going to it costs less than a day. Neither is built.
Verified, on the server: the start line after the move showed every optional service connected and took 15 seconds from launch to ready, against half a minute on the laptop; the host's check passed; from outside, /health answered, the sign-in page refused an address with no waiting sign-in, and every other path answered "not found"; a meeting brief for the invited person read their mail and calendar through the connector and was delivered to their chat. Not tested: a restore from a photograph of the disk; a deployment of an older image; the program running out of memory with swap on.
7.11Two things that are easy to get wrong
The clock
Servers keep time in UTC. The owner does not live in UTC. On a laptop this needs no thought, because the laptop's clock is already the owner's. On a server, a program that reads the machine's clock is silently wrong by the owner's offset: every reminder late, every message stamped with the wrong time, every "tomorrow" possibly the wrong day, and no error anywhere. For an owner five and a half hours ahead of UTC, "remind me at 7am" fires at half past twelve.
The fix is one clock for the whole program, pinned to the owner's zone by a setting. In odysseus/config.py:
def make_clock(tz: str = ""):
"""The one clock used for message stamps, memory dates and the schedule: local wall-clock time, no zone."""
if not tz:
return datetime.now
from zoneinfo import ZoneInfo
zone = ZoneInfo(tz)
return lambda: datetime.now(zone).replace(tzinfo=None)
main builds this once and passes it to everything that needs the time. The daily budget uses the same zone, so "today" ends at the owner's midnight. The hosting configuration sets ODYSSEUS_TZ, and the deploy guide tells anyone copying it not to skip that line.
Who owns the disk
A freshly attached volume arrives owned by the administrator, and the program runs as an ordinary user who cannot write to it. A program that cannot write its memory fails at its first save. So the image's start command runs one step as administrator, hands the data folder to the program's user, and then starts the program as that user:
CMD ["sh", "-c", "chown -R app:app /data && exec runuser -u app -- python -W ignore -m odysseus"]
Verified On the server, the data folder and the files in it belonged to the program's user.
7.12The theory
This section states the chapter's claims in the terms of the model, and separates what the program guarantees from what was observed.
Two lifetimes. Split the program's state into Σdisk, the data folder, and Σproc, what the running process holds. A restart returns Σproc to its starting value and leaves Σdisk as it was, less at most a half-written last line of the journal. The rule that every check depending on surviving state must survive too is Definition 5 read across restarts: T may be emptied only when the context is, so once the conversation lives in Σdisk, so must T. The approval is the converse case: Definition 6 binds a yes to one call shown in its context, and an approval kept on disk could be spent in a context the owner no longer sees, so it dies with the process on purpose.
Knowing what was cut off. unfinished computes derived state in the sense of Definition 8: a fold over the journal from the last start line, returning the task whose task_start has no task_end, the previews of queued lines with no dequeued, whether a question was open, and a job in the background that had not ended. It is correct because the conversation writes ahead: task_start and queued are appended before the work they describe. It is correct only if every task_end it counts belongs to the task it closes. Writing that hypothesis down found two places where it failed: the line a contact lookup writes, marked leads, closed the open conversation task too, and only the latest job in the background was kept, so with two running at once the end of either cleared both. Both are corrected. A weaker form of the second remains: the lines carry no name for a background job, so when one of two ends, the one that began first is taken to be the one that ended. This is Property 3's warning in practice: from completions alone no function could tell a task that never began from one that died halfway.
Let a conversation task be cut off by a restart after it executed calls c₁, …, ck, the last perhaps with its effect done and its result unrecorded. The recovery path of the next process executes no tool call on the task's behalf; its only output is one message to the owner. So each ci has run exactly as many times after the restart as before it, at most once, and a restart cannot turn one send into two.
Argument. Recovery reads the journal, computes unfinished and builds the notice from the previews it returns. No code path leads from there to the agent loop or the gate. The waiting messages are named and not queued again, and the task and the queue were in Σproc, so nothing remains that could run them. Text sent to the owner is not an effect in the sense of Definition 2.
Where it fails. The property is about effects, not about the notice. The notice is sent before the start line is written. If sending fails, the failure is journalled and the start line is written anyway, so that task is never reported; if the program dies after sending and before the start line, the next start reports it a second time. And the property covers conversation tasks only: reminders and routines that fall due are run again on purpose, at least once (Chapter 6).
Why announce and not resume. Let p be the probability that the cut fell after a send took effect and before its result was recorded. Resuming duplicates the send with probability p, by a program that cannot see whether it happened. Announcing duplicates nothing, and leaves the owner with the same uncertainty plus what the program lacks, the means to look at the world before asking again; a send asked for again passes the gate and is shown. Resuming would be safe for calls that only read or are idempotent. The program does not sort calls that way, so a task that only read also costs the owner a request.
What was measured. A start took about a minute on the laptop before the change and 31 seconds after it, and 15 seconds on the server, one start each. Resuming let "Looks good, send it" refer to the earlier draft in two runs of an evaluation scenario.
| Claim in this chapter | Kind | How it is known |
|---|---|---|
| A restart never repeats an interrupted task's tool calls | Property | Argued from the recovery path |
| An interrupted task and the messages waiting behind it are named at the next start | Property, if the notice can be sent and no contact lookup ended during the task | Derived from the journal; unit tests on a shortened journal |
| A message more than ten minutes old on arrival is not acted on | Property of the code | Unit test for WhatsApp only |
| A resumed conversation lets "send it" mean the earlier draft | Measurement | Two runs with the real model |
| A start takes about half a minute on the laptop and 15 seconds on the server | Measurement | One start each; varies by several seconds |
7.13What goes wrong
Two failures have been described already: restarting in place, which left process-wide state shut and failed silently, and start-up code that no test ran. Three more follow.
Nothing announces a dead program
The program was deployed to a hosting service and started there. It wrote its start record to the mounted disk, showing mail, the browser and file reading connected, and handled one message. The machine was checked thirty seconds after launch and found running. At five minutes the hosting service stopped it, under a limit on new accounts with no payment card. Nothing in the deploy output said so; the only trace was a line in the machine's log. The copy on the owner's laptop had been stopped beforehand, correctly, so that two copies would not compete for messages. For some minutes no copy was running anywhere, and nothing said so. The owner found out by sending a message and getting no answer.
Three lessons follow, in order of generality. A check at thirty seconds says nothing about minute five. Stopping the old copy before the new one has proved itself removes the fallback at the moment it is most likely to be needed. And a system that announces its own failures still needs something outside itself to announce its death.
The incident exposed a second gap. The journal recorded that the server's one task had finished and not whether its reply was sent, so whether that reply arrived is unknown. A record of finishing is not a record of delivery: every reply is recorded as sent, with the number of parts, or as failed, with how many parts got out. The watcher from outside is not built.
The owner must be told of a lost conversation
When a saved session cannot be resumed, the runner writes an error to the journal and starts afresh. If the owner heard of this only when a restart had also interrupted a task, a quiet restart with a damaged transcript would leave the owner's next "Looks good, send it" facing a model with no idea what "it" was. So the program sends one line in that case too: it was restarted, could not pick up the earlier conversation, and still has what it remembers. It does so only where the agent connects at start, which is the host's own assistant; an invited person's resume is tried at their first message, and a failure then is in the journal only. The memory block is shown again, so lasting facts survive; the thread does not.
Waiting messages must be written down
The owner of a message queued behind a task has been told "Noted. I'll do this as soon as the current task is finished." Held only in the process, that promise would vanish in a restart without a word. So each waiting message is journalled as queued, so that a restart can name it in the notice.
7.14How to test it
A test of this part must check that state survives a new process reading the same files, that what cannot survive is announced, and that the program can assemble itself at all. The tests use a trick worth copying: a "restart" is simulated by building a second runner or conversation on the same folder, which is exactly what a new process does, without starting one.
tests/test_durability.py(eleven tests) covers the waiting queue andstop,/new, the session identifier being saved, picked up and passed asresumewith transcripts inside the data folder, a damaged session file, and every case of the restart notice described above.tests/test_startup.pychecks that the program assembles with everything and with nothing optional, and that the supervisor starts a fresh child each time one exits with 75 and stops on any other code.
What the tests do not show: that the library actually resumes a real session, that the notice reaches a phone after a real restart, or that anything works on a real server. Those need live runs. One exists for resuming: an evaluation scenario in which the owner says "Looks good, send it" after a restart sent the email shown before the restart, in two runs with the real model (Chapter 18). Without the kept session, the agent could only ask what "it" was.
Verified The tests in tests/test_durability.py and tests/test_startup.py pass. Resuming a conversation after a restart worked in an evaluation scenario with the real model, two runs. Restarting in place worked live nine times in a row; the supervisor that replaced it is tested by a unit test only. The image built, and the program started on a hosting service, connected to the agent library, wrote to its volume as the right user, and handled one message.
The program runs on a server, and what follows was observed in its first day there. The first deployment was stopped by the host at five minutes because the account had no payment card. The second is the move described above: the data folder arrived whole, the conversation's transcript was found under its new name, and scheduled work for two people ran. Nothing here has been watched over a week, and no crash of the hosted program has happened yet, so the host's restart of a crashed process is the host's claim.
Not tested A restart through the supervisor in the real chat. The restart notice reaching the owner's phone after a real restart mid-task. A reminder set by the owner firing at the right local time on a server. A conversation kept for weeks. Cost counted correctly across a resume: the library reports a running total per session, and whether it continues after a resume has not been measured (Chapter 20). The stale-message rule for Telegram: it is written and has no test, because the stand-in for Telegram does not carry dates (the WhatsApp version has a unit test). Not built: a copy of the data folder anywhere but the one disk and the host's daily photographs of it, and anything outside the program that notices when it has died.
7.15Where this sits in the literature
[Gray 1985] analysed failure reports from a commercial fault-tolerant system and found that administration and software, not hardware, caused most outages, and that many software faults were transient, so that restarting and retrying cleared them. The restarts in this chapter fit that profile: updates, a change of configuration, a host's limit, a fault in start-up code, and none from hardware. [Candea and Fox 2003] proposed that a component's only way to stop should be to crash and its only way to start should be to recover, so that recovery is exercised every time. This program does half of that. Every start runs recovery, reading the journal before writing anything, but stopping has a clean path, the clean-up at the end of main, that a crash skips. The tracing client shut by one clean-up and never reopened is a failure of exactly the kind a crash-only design removes, since there would have been no clean-up to get wrong. [Armstrong 2003] structures a system as isolated processes under supervisors that restart failed workers. The supervisor here is the smallest instance, one parent and one child, and it differs in one respect worth noticing: it restarts the child only when asked to with code 75, and leaves a crashed child to whatever runs the supervisor.
The decision to announce and not resume is the argument of [Helland 2012]. When a process can fail between acting and recording, work is done at least once unless the action is idempotent, and only the receiving side can make it so. [Stripe undated] documents the standard remedy, a key chosen by the client that lets a request be retried after a lost connection without repeating its effect. That remedy is stronger than anything in this chapter: with it a restart could resume a payment safely. The services this program sends through are given no such key, so it hands the decision to the owner, who can look at the world. [Garcia-Molina and Salem 1987] split a long transaction into steps, each with a compensating action. A sent email has no compensation, which is why the saga pattern does not help with the step that matters most here, though it would fit a task made only of changes to records that can be put back.
The case notes about the hosted program are about observation. [SRE book, monitoring] argues that alerts should be actionable and based on symptoms. The host's check of /health is a signal about a cause (the process answers inside the host's network), and the chapter records it passing while nobody outside could reach the program. A symptom-based check would ask the question the owner cares about, whether a message gets an answer, from outside. [SRE book, embracing risk] gives a method for deciding how much unreliability is acceptable: state an objective and spend the error budget it allows. No such objective is stated for this program, so whether three restarts a day of half a minute each are acceptable has no answer here, and one of the problems below asks for one.
Testing recovery is its own subject. [Basiri et al. 2016] describe experimenting on a running system by injecting faults to build confidence in its resilience. The tests here simulate a restart by building a second object on the same folder, which tests the reading of state and not the moment of failure; killing the process at random points while work is in flight is the experiment the chapter has not run.
What is not settled is whether an agent can find out from the world whether an interrupted act took effect, for services that offer no key, without asking a person. Reading a sent folder works for one kind of act and one provider; no general method is known, and for that reason this chapter announces.
- Sort state into what dies with the process and what lives on disk. Put everything that must last in one data folder, and make every check that depends on surviving state survive too.
- A conversation survives if two things are kept where data survives: the session identifier and the library's transcript. If it cannot be picked up, start a new one rather than fail every message.
- An interrupted task is announced, with its first words and any messages that were waiting, and not resumed: the program cannot know how far it got, and doing something twice cannot be undone. Approvals die with the process, and the notice says so.
- A message more than ten minutes old on arrival was written for a moment that has passed. Report it; do not act on it.
- Restart by exiting to a supervisor that starts a fresh process. Restarting in place leaves process-wide state behind. Better still, rebuild only the part that changed and leave the process alone.
- Long polling needs no inbound port. A webhook channel opens one, and a sign-in that returns to the program completes only on the machine the program runs on.
- Pin the clock to the owner's zone, and hand the data disk to the program's user at start. Then check again after ten minutes, not thirty seconds.
- Move a live assistant in this order: build the new home with the program held still, rehearse the copy, wait for nothing to be in flight, stop the old copy and check it is gone, copy for real, start. Then ask from outside whether it can be reached, and measure its memory there, not on the machine it came from.
- The copy left behind holds renewal tokens that are good once. Keep it as a backup; do not run it.
Review
- The session identifier is kept on the volume and the transcript is left where the library normally writes it, inside the image. Describe what happens at the next update, step by step through
_ensure, and what the owner experiences. - Give a case in which resuming an interrupted task automatically would do harm, and one in which it would be harmless. What would the program need to know to tell them apart, and where could it get that knowledge?
- Why does
unfinishedtreat astartline as clearing everything before it? Construct a journal in which removing that rule produces a wrong notice. - The time zone setting is left out on a server. At ten in the evening local time, five and a half hours ahead of UTC, the owner asks for a reminder "tomorrow at 7am". Trace what goes wrong and when the reminder arrives.
- Write a test for the Telegram stale-message rule. The stand-in does not carry dates: what would you add to it, and what should the test assert about a backlog of five old messages?
- Extend the supervisor so that a child that crashes three times within a minute is not restarted again, and the owner is told by a message sent from the supervisor itself. What does the supervisor need that it does not have now, and what must it still never hold?
- The old copy of the data folder is started by mistake a week after the move, runs for an hour and is stopped. List what the hosted copy has lost, when the owner will first notice each loss, and what the program could write at start-up to refuse to run from a folder that has been moved away.
Analysis
- Suppose updates restart the program three times a day, and count as unanswered only the time a start takes. (a) Compute the seconds a day unanswered with a start of 31 seconds (the laptop after the change) and of 15 seconds (the server). (b) An objective of answering 99.9% of the time over a 30-day month allows how many seconds unanswered? Which of the two meets it from updates alone? (c) A message sent at the instant a restart begins reaches the new process when it starts polling. How long would a start have to take for that message to be reported and not acted on?
- State the hypotheses under which the restart notice reaches the owner exactly once. Using the order of steps at start-up described in the theory, give one execution in which it is sent twice and one in which it is never sent, and say what the journal holds at the end of each. Then propose the smallest change to the order that removes one of the two, and say which it removes and at what cost.
- The chapter keeps several things on disk besides the journal: the session file, the transcripts, the file of hashes, the tokens and the schedule's own table of runs. For each, say whether it is derived state in the sense of Definition 8. For one that is not, describe a crash after which it and the journal disagree, and say which of the two the program believes when it starts again.
- A send is cut off by a restart, and p is the probability that it had taken effect. Compare three policies by the expected number of duplicate sends and of sends never made, counting the owner's own choices as part of the system: resume the task; announce it (this chapter); and look in the sent folder before deciding. State what the third assumes about the world it reads, and give an execution in which that assumption fails and the third policy does worse than announcing.
Design
- A new requirement: the assistant must run on two machines, so that one takes over when the other dies, and never with two copies polling at once. Design how the copies agree which one runs, what the second watches, and what happens to a task in flight at the moment of the switch. State what is guaranteed (at most one poller, nothing done twice) and what is given up (the length of the gap, and what is lost in it).
- Design an outbox for sends: a journal line written before each send and one after, so that a send cut off by a restart can be checked and not merely announced. The mail service offers no idempotency key. Say what the program can look up afterwards to decide whether the send happened, what it does when it cannot tell, and which cases still end in an announcement.
Reading
- [Candea and Fox 2003] argues that the only way to stop a component should be to crash it and the only way to start it should be to recover. In about four hundred words: what it claims; why it matters for this chapter's supervisor and for the clean-up that left the tracing client shut; where you were not convinced that a personal agent should give up a clean shutdown; and what you would change or measure next.
- [Helland 2012] argues that messages arrive at least once in practice and that processing must tolerate duplicates. In about four hundred words: what it claims; why it matters for the decision to announce an interrupted task and not resume it; where you were not convinced that the argument applies when the receiver is a person's mailbox; and what you would build next so that more interrupted tasks could be resumed safely.
Open
- (Hard, open.) Design something outside the program that notices when it has died and tells the owner, without opening an inbound port on the server and without a second copy polling Telegram. Consider what "alive" should mean (the process exists, it polled recently, it answered a message), who sends the alarm, and how the alarm itself is tested.
- Can an agent decide, from the world alone, whether an act cut off by a crash took effect, for services that offer no idempotency key? State the problem for a class of acts you choose (sending mail, changing an event, adding a record), and the evidence each service lets a program read afterwards. Progress would be a method that classifies interrupted acts as done or not done, with an accuracy measured over many runs in which the program is killed at random points against stand-in services, and an honest third answer when it cannot tell.