Storage consistency
Data model: Session storage.
Registry timestamps and snapshots
updated_at is the last content append, not the last metadata write.
| Operation | Contract |
|---|---|
_persist_meta | Rename, pin, read markers, branch markers and HEAD keep the timestamp. Append advances it. Branch records come from disk (Branch records). |
_index, list_sessions() | Readers get a point-in-time copy of each row. Concurrent creation, mutation and deletion cannot tear fields or break iteration. |
| Deferred flush | An older snapshot cannot overwrite a newer one. Mutations during publication stay dirty for the next flush. |
State flow
- Appending generates one timestamp for session metadata and its registry entry.
- Registry mutations hold the state lock. Listing copies rows under it, then filters and sorts outside.
- A writer takes the write lock, captures JSON and clears only the covered dirty state under the state lock, then releases that lock.
- Atomic publication runs outside the state lock.
- A concurrent mutation marks the registry dirty again; a timer or exit flush publishes it.
Failure and compatibility
| Case | Behaviour |
|---|---|
| Disk failure | Warns; memory keeps serving; the next mutation or flush retries. |
| Returned rows | Copies. Caller changes do not reach the registry. |
| Creation | An explicit historical timestamp is kept. Rebuilds do not migrate the schema. |
| Sorting | Descending updated_at; absent counts as zero. Wire shape unchanged. |
Mechanisms and rejected alternatives
| Item | Detail |
|---|---|
| Boundary | As in SessionMemoryIndex: update state under lock, file I/O after release. |
| Locks | Standard threading: one state lock for dictionaries, dirty state and timers; one write lock for publication order. |
| Replacement | atomic_write_text |
| Rejected | Global lock around every store call; synchronous registry write per append; a new timestamp field; a database; cross-process registry locks; new background services. |
Registry acceptance
| Public entry | Scenario | Result |
|---|---|---|
update_session | Rename, pin or mark read | Timestamps and list order unchanged |
append_message | Append content | Metadata and index advance together; list uses the new time |
list_sessions | Mutate a returned row | Next list unaffected |
| Deferred flush | Mutate while an earlier snapshot writes | Next flush keeps the new fields in index.json |
| Update, list and flush together | Readers and writers run concurrently | No iteration errors; JSON parseable; memory and disk agree at the end |
Branch records
A branch record (meta["branches"][tip]: name, auto-name state, turn count, archive flag) has several writers that can land at once: close_agent archiving a running agent, the turn it cut off finishing (carry_branch_entry, bump_branch_turns), the background auto-namer (set_branch_name), a rename from the Web, a delete. Each one changes only the fields it owns, on the record as it is on disk.
| Rule | How |
|---|---|
| One merge point | _update_meta reads meta.json inside the session write lock, applies the writer's change, writes, then copies only the written keys into the cache. No writer replaces a record with a copy it read earlier. |
| Whole-cache writes | _persist_meta, commit_turn, append and node deletion write the cached meta with branches, branch_refs and active_branch_id taken from disk (_meta_for_write), so a cache that missed another writer cannot put an old record back. Append moves the branch records on the disk copy it read inside the lock. |
| Switch and rewind | A branch switch and a rewind name their change instead of carrying copies of the maps: compare_and_set_head applies branch_checkout (apply_checkout) and branch_record_moves to the record it read inside the lock. Whole branches, branch_refs or active_branch_id values in its update are dropped, including ones in an intent journaled before this rule. |
| One name source | Every reader, the branch list for selected and unselected branches alike, takes a branch's name from its record at its tip (branch_record). A tip record always wins over a parked copy, and a background run carries its unselected branch's record along. |
| Record follows the tip | Every message a branch adds moves its record in the same write: follow_line for the selected branch (inside advance_branch), carry_branch and point_branch for another. A record already at the new tip is merged into it, its own fields winning. |
| Late tip | A write addressed to a tip the branch has moved past (the message its latest turn extended, or that turn's user message) goes to the branch's record now (_record_tip). Settings and the worktree binding are keyed by branch id and never move. |
| Shared tips | Branches rewound to one message cannot share a tip record: the selected one owns it; each other parks its own on its ref as label (written inside the lock when left, put back when selected). |
| Archive is final | A record that is archived keeps archived, archived_at and archived_reason whatever a later write sets. |
| No resurrection | A turn count or automatic name for a message that is no longer in the conversation writes nothing. A branch write never creates a conversation. An archive or a plain name may open a record for a reply admitted but not yet written. |
Why the archive was lost
The old writers merged the record in the cache, then wrote the whole cache. In between, a writer that reads meta.json under the lock (the finished turn's update_branch_fields) replaced the cache with the disk copy, which did not hold the archive yet. The archive's own write then saved a cache without it, and the auto-namer later opened a fresh record.
Branch settings (update_branch_config), the worktree binding (update_session) and the Goal (update_session_dict with a version check) were already read-modify-write on disk under the lock.
Names were lost the same way on a branch switch. The switch read the whole branches and branch_refs maps before the lock, overwrote the target's record with the copy parked when it was left, and wrote both maps back with the HEAD move.
So a rename of an unselected branch, which the list did not show because it read only the parked copy, lost its name and lock on the switch; automatic names too.
A rename while a turn ran lost the branch's turn count. The selected branch's record stayed at the old tip until the turn ended, the rename opened a second record at the tip on screen, and the turn's end carried that one.
A Worker that hung between moving a branch's ref and its record left two rows: one at the old position named by a raw id, one at the reply with a name and no branch id.
Loading does not repair the pair. A ref behind a continuation is also what a rewind leaves, and the reader cannot tell the two apart without guessing. Ref and record now move under one lock.
Acceptance: archiving 60 tips while two threads write the session and count turns loses none; two stores on one folder (two processes) archiving and naming the same tips keep both fields; a late un-archive, a late name and a late turn count after a delete change nothing.
Atomic merged-head updates
mark_merged(session_id, head_ids) is a set union. Child-agent completion, task runners and Web branch actions can call it at once; every update survives.
| Property | Requirement |
|---|---|
| Atomicity | Read from disk, deduplicate, append and write in one _update_meta section under the session write lock. |
| Order | Existing order kept; new, nonempty, stripped IDs follow in input order. |
| Idempotency | Repeats add nothing. No new value, no disk write. |
Scope and acceptance
- Two concurrent callers with different heads: both present in memory and after reload.
- Whitespace and duplicates keep normalization and idempotency.
Store lock scope
Slow I/O for one session must not block others.
| Resource | Lock | Requirement |
|---|---|---|
_locations, _sessions, LRU order | _lock | Memory only: no directory scan, atomic write, fsync or recursive delete. |
| Load, rebuild, delete and invalidate one session | The conversation's process lock (conversation_lock) | Same session serialized; different sessions concurrent. One lock per conversation per process, shared by every store; it is the first half of the write lock. No transaction layer. |
locations.json publication | _locations_write_lock | Capture under the state lock, write after release. An old snapshot cannot overwrite a newer one. |
SessionMemoryIndex persistence | _persist_lock, then idx._lock | Lock order and stale-rebuild semantics kept. No I/O under idx._lock. |
Scope and acceptance
File formats, LRU capacity, deletion semantics, cross-process stale detection and Windows behaviour do not change.
- While A blocks in
read_metaorlist_history, B's cached read finishes in bounded time. - While A's recursive delete blocks, B's read does not wait.
- Concurrent first loads publish one cached object; loading cannot republish a deleted one.
- After concurrent location updates for two sessions, reloaded
locations.jsonholds both.
Conversation lock order
Every path takes a conversation's locks in one order, and no path holds one while waiting on a model, the network or another conversation's lock.
- The process lock: a reentrant lock per conversation, shared by the store, the server and the job, event and checkpoint helpers of this process.
- The flock on
projects/.locks/<id>.lock, throughsession_interprocess_lock, which takes step 1 first. The holder keeps one descriptor; nested acquisitions in its thread count on it instead of opening a second descriptor, which would wait on the first. - Inner locks: the index's
_persist_lockand_lock, the store's maps, registry files, the rewind intent lock and the workspace lock.
A rewind, and a revert or reapply of a turn's files, holds steps 1 and 2 from looking up its idempotency key, through its plan and intent, to its outcome, and recovery replays the journal under them, so recovery never replays a rewind still being applied.
A second request with the same key waits for the first and returns its recorded outcome, committed or failed: it never plans against the state the first one left, never reads an unfinished intent as one needing recovery, and never applies a second time.
A rewind or a revert also applies inside its recovery scope: when its conversation leaves the store cache while it holds the workspace lock, the reopen its head check makes does not replay its own intent, which would take the workspace lock a second time and wait on itself.
Both waits are bounded (60 s by default, shorter where a caller passes a timeout): past it, SessionLockTimeout names the conversation and the holder, a thread of this process or another process, and the request fails instead of blocking a Worker thread.
Why, and acceptance
The branch-record merge put more writes under the flock, and two paths took the halves in opposite orders: a branch switch held the store's lock and waited for the flock, while the page load held the flock and waited for the store's lock to read the conversation. A run's admission did the same.
Every later request on that conversation queued behind the pair and the Worker stopped answering.
| Scenario | Must hold |
|---|---|
| Sixteen threads on one conversation with five branches: turns on two branches, renames, a model change, a branch deleted, concurrent switches, a rewind plan, page loads, run admissions, cache misses | All finish, 200 runs in a row; a watchdog fails the test with the stuck stacks instead of hanging it |
| A conversation held by a stuck thread | The next writer gets an error naming it within its wait; other conversations are not held up |
| An error between acquire and release (a refused switch, a stale plan) | Releases the lock |
| Two processes and two threads append to one conversation | Every message lands; a process killed while it holds the flock frees it for a writer already waiting; a revert whose conversation leaves the cache mid-apply commits |
| Two rewinds, or two reverts, with one key | While the first is paused before or after writing its intent, the second waits and then returns the first's committed outcome; after the first committed or failed, the second returns that outcome; files and head change once |
Not on the event loop
The Worker's event loop serves every connection, so no request is to wait for a conversation's lock on it: the work that reads or writes a conversation runs in a worker thread, so a conversation held by a turn, a cold first load or another process delays the request that needs it and nothing else.
| Where | How |
|---|---|
| WebSocket actions | The handler stays a coroutine for its frames; the store work between them runs in the conversation's lane (run_for_conversation), built into one plain function when a frame needs many reads (_session_loaded_data, run_state_data, _checkout_branch, _attach_branch). |
| HTTP routes | A route with nothing to await is a plain function, which FastAPI runs in its thread pool; one that awaits runs its store calls in the conversation's lane. |
| Execution controls | submit_execution_control (Stop, pause, continue, step, steer, answers) reads and writes the execution's records in a worker thread, step by step in the order the command always had, under the same command id; only the owner's signal, an activation and a steer's attachments are awaited on the loop. A Stop reaches a running owner as soon as its command is written, and only once. The Agent driver's activation reads and starts its owner thread in a worker thread too. |
| Many waiters | A lane is at most LANE_WIDTH (2) threads of a pool the lanes share (POOL_SIZE, 64), not the loop's default pool. Requests beyond it wait on the loop, holding no thread, in arrival order, so one held conversation never takes the threads of the others, and work waiting in asyncio.to_thread elsewhere never holds up a lane. A thread that already holds a conversation's lock runs the work in place. |
| Function runs | POST /api/function/{name}, the Retry of a function run and a typed local command call run_agent_method_call (session, run slot, execution record, code node) in a worker thread. |
| A site that is missed | The server hands its loop down to the lock (watch_event_loop; the store never imports the server). A lock taken on that loop logs a warning, once per call site with its stack (_note_event_loop_acquisition), so the site is found and moved. |
Taking a run slot waits for the lock with the store's own budget (admission_lock_wait, 60 s), not a quarter of a second: a holder does file work only, and the first load of a large conversation can take longer than that.
A lock still not had then is answered conversation_locked (retryable, nothing started, the text kept for the next send); only a slot that is held is run_active, which a client answers by queueing the message behind a turn.
A turn nobody typed takes the slot through run_slot.reserve, whose lock_wait bounds the wait (0: none at all). Each caller answers a lock not had in its own way:
| Caller | A lock not had |
|---|---|
| Room event (ambient) | Waits for nothing: neither the conversation's lock, nor a finishing turn, nor a channel turn running in the conversation. It is skipped, as when the slot is held. |
| Channel message | Waits for the lock within the slot's 30 s; past it the sender is told the message was not delivered and can be sent again. |
| Reminder wake, handed-over message | Counts as busy: start_owner_turn_when_free tries again until its wait ends. |
| OpenAI-compatible API | 503 conversation_locked; a running turn stays 409 conversation_busy. |
Why, and acceptance
Page loads, run-state probes, branch switches, renames and settings read a conversation inside async def handlers. A turn holding the conversation, or another process writing it, froze every connection for up to the lock's 60 s wait.
Slot admission waited only 0.25 s and read a timeout as a running turn, so a send to a cold, large conversation was refused run_active and re-queued behind a turn that did not exist.
Codex keeps one writer lock file per thread (~/.codex/thread-writer-locks) and serves its clients from an async runtime; a request waiting for a thread's writer waits in its own task. The same rule here: the loop never waits for a conversation.
| Requests | Must hold |
|---|---|
| Load, run state, branch switch, rename, full tool output, Sandbox, mark read | Each waits for it while a 10 ms heartbeat on the loop never stalls past a quarter of a second; the same read made on the loop stalls it for the whole hold |
| Routes a page calls on opening a conversation: context coverage, context breakdown, branch tokens, session tokens | The same |
| Attach branch, the stream resubscribe, project binding and move, extra folders, flags, context commits, node deletion, channel binding, compact, the in-place fork, export, rewind points | The same; noting a queued message (goal_queue) never waits at all |
| A Stop of a turn that never started | Writes its cancelled reply while the conversation is held, with the loop's heartbeat under a quarter of a second |
| Five copies of one Stop to a running owner | One command, delivered once, in under a second, also when the owner takes 50 ms to answer |
| Forty requests waiting on one held conversation | Another conversation's run state answered in under half a second; with the loop's default pool it times out |
| A room event; a channel message | The room event takes no wait on a locked conversation or a busy channel turn; a channel message whose conversation stays locked is answered as not delivered |
| A slot request while the lock is held for 0.6 s | Admitted once it is free |
| Past the wait: a send, a branch send, an operation, a multi-branch operation | Each answers conversation_locked and takes nothing; a held slot is still run_active |
Cache snapshot freshness
- Warm rebuilds and first loads capture the disk fingerprint before reading history and metadata.
- The rebuilt index records that captured fingerprint, never a newer one.
- A concurrent atomic replacement changes the fingerprint, so the next public read rebuilds.
Acceptance
Two real SessionStore instances. A write lands after a reader loads the prior snapshot and before it marks synchronization; the next get_nodes or get_session sees the new value, on cached and first-load paths. Cancellation retry keeps its deadline and observes the actual cancelled file.
Windows session directory removal
Explicit deletion, expired-session cleanup and capacity cleanup share one platform adapter (openprogram/host/_platform/filesystem.py).
| Failure | Action |
|---|---|
| Regular Git object, read-only attribute | Clear the attribute; retry that removal once. |
| Other permission failure | Caller's best-effort behaviour. ACLs untouched; links not followed. |
Acceptance
Public reopen and delete_session with a read-only Git object; the directory is really gone, not only absent from the index. Native Windows CI is required. Follows the shutil read-only removal recipe with Python 3.11-compatible callbacks.
Implementation status
| Source | Responsibility |
|---|---|
openprogram/state/store/session/session_store/ | Timestamps, registry locks, snapshots, deferred flush, merged heads and store locks |
openprogram/state/store/session/session_node_writer.py | One activity timestamp per append, shared by metadata and index |
tests/component/store/session/test_session_index_consistency.py | Public regressions for ordering, snapshots and concurrent writes |
openprogram/state/store/session/files/session_lock.py | The conversation lock: process lock, flock holder record, bounded waits |
tests/component/store/session/test_session_lock_stress.py | Many threads on one conversation; a stuck conversation errors |
tests/component/store/session/test_session_lock_processes.py | Two processes on one conversation; a killed holder; a revert that misses the cache |
openprogram/interfaces/server/ws_actions/, openprogram/interfaces/server/routes/ | Store work of the handlers in worker threads |
openprogram/interfaces/server/server_runtime/session_lifecycle.py | Slot admission waits for the lock; conversation_locked apart from run_active |
openprogram/state/store/session/conversation_work.py | A conversation's lane in the lanes' own pool |
openprogram/runtime/execution/control/ | Control commands' store work in the execution's lane (off_loop) |
openprogram/interfaces/channels/inbound/_conversation.py, openprogram/runtime/conversation/turn_admission/owner_turn.py | A lock not had: a room event skips, a channel message is not delivered, a wake tries again |
tests/component/webui/chat/test_conversation_lock_off_loop.py | A held conversation and the loop's heartbeat for every handler; a Stop; forty waiters; a slow lock admitted; a lock not had reported as locked |
tests/component/store/session/test_conversation_work.py | Lane width and order, cancellation, context, a held lock, a fork, a full default pool |
Not yet in a lane: store work of handlers outside one conversation (settings, catalog, recordings) still runs through asyncio.to_thread on the loop's default pool, off the loop but unbounded; a Job's wait-resume scheduler is called on the caller's loop.