Repository navigation
Sessions: turns, forks and event replays no longer load a whole session or log (#254) - #1102
Conversation
Each turn decoded every message of its session twice. Loop._turn counted the user turns it passes to memory by loading the whole session, and the memory checkpoint loaded it all again to keep the last 40 messages. /handoff counted user turns the same way. The cost grew with the session. SessionStore.user_turns now counts in SQL with the same rule: a user message counts unless its context note is one Python reads as true. SessionStore.last_messages reads only the newest rows through the (session, seq) index. Its text and place match draft #903, so the two merge cleanly. Results are unchanged: the tests compare both helpers with the full load on sessions with notes of every falsy and truthy kind and an undone tail, and a turn on a 1,300-message session now decodes at most 45 messages. User guide: none. Developer guide: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QDoXr7oqhY27xUfi67tUd5
SessionStore.fork wrote each copied message through append_message, so every copy took its own write transaction, its own seq lookup and its own session update, and each summary took another statement. A large fork was slow, and a fork that failed partway left a new session that held only part of the thread. The fork now runs in one write transaction. It adds the session through the same insert as create_session, builds every copy the way append_message did, and writes the copies, their search rows and the summaries that still fit with executemany. A failure rolls all of it back. The tests compare the new fork with the old one row by row (data bytes, seq, copy_pos, search text, summaries) for thread, scheduled and private parents, with and without a fork point. User guide: none. Developer guide: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QDoXr7oqhY27xUfi67tUd5
The hub's replay (SqliteLog.read), trace and /handoff called events_since with a limit of 2^30, so one read decoded every matching event at once. A Subscription then copied that list into its backlog, so a client that subscribed from seq 0 waited for the whole log and the core held all of it until the client caught up. SessionStore.iter_events reads 1,000 events at a time by seq and stops at the newest seq at the call, so it returns what one read at the call returned. It reads the first page at once, so a bad since still fails when the caller asks. The three callers use it, and a Subscription keeps the log's iterator as its backlog. The queue is still registered before the backlog is read, so the no-gap, no-repeat promise holds. The replay test subscribes from seq 0 across three pages while live events publish and gets every seq once, in order. A read that also keeps the events of no session (with_global, the hub's replay) is now two index searches joined by UNION ALL. Its OR form made SQLite sort every later event of the session on each call, so a read page by page would have grown with the square of the log. With the change, 100,000 events read page by page in the same 0.74 s as one unbounded read, with 1.6 MB at the peak instead of 88 MB. In Subscription.next the event now reads as Event | None from its first assignment, which matches the queue, so the one mypy diagnostic there is gone and the type baseline drops it. User guide: none. Developer guide: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QDoXr7oqhY27xUfi67tUd5
Two parts of the #254 W2-4 change had no test that fails without them. /handoff could go back to loading the whole thread to count its user turns, and the tests would still pass: they checked only the count the loop passes to memory. The events_since read that also keeps events of no session could go back to its OR form, which sorts every later event on each call, and the tests would still pass, because both forms return the same rows. The first new test runs /handoff on a 30-turn thread and checks that it counts the same user turns without a whole-thread messages() load. The second counts SQLite's steps for one 10-event page at 2,000 events and again at 20,000: the UNION ALL form costs the same both times, and the OR form grew tenfold. Each test fails with its part of the change undone. User guide: none. Developer guide: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QDoXr7oqhY27xUfi67tUd5
The stdio transport sent events.subscribe through the dispatcher, whose one-shot reply decodes every event since the cursor and turns each into a dict. The transport then dropped that reply and streamed from a Subscription. So a stdio client that subscribed from seq 0 still made the core decode the whole log at once, and paging the Subscription's backlog did not help it. The transport now decodes the line itself and opens the Subscription at once. The Subscription reads its first page there, so a since the log cannot read still gets the same typed "internal" reply and the transport lives on. The feed takes that Subscription and opens a new one only after a stream ends for lag, as before. Every other command still goes through the dispatcher. A Subscription whose first read fails now takes its queue back out of the hub. Before, the queue stayed registered and filled with every later event until the lag rule dropped it. The new tests subscribe over stdio from seq 0 on 3,000 events: the first event goes out after one page is decoded, where main decoded 4,000. A since past SQLite's range gets the typed reply and leaves no queue in the hub. User guide: none. Developer guide: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QDoXr7oqhY27xUfi67tUd5
After the paging change, a Subscription read its backlog from the log directly, while Hub.since read the same events through the hub. Open PR #946, and the PRs stacked on it, filter what the hub replays by session owner in Hub.since, and a Subscription there takes its backlog from Hub.since. Merged with this branch in either order, git joins the two with only an import-line conflict, and the backlog would then skip the owner filter without anyone seeing it. Hub.replay now hands out the log's iterator, Hub.since lists it, and a Subscription takes its backlog from it. A rule on what the hub replays has one place, and #946's change to Hub.since now meets this one on the same line, where whoever merges second sees it. The new test puts a filter in Hub.replay and checks that Hub.since and a subscription's backlog both apply it, across more than one page. It fails with the backlog read from the log directly. User guide: none. Developer guide: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QDoXr7oqhY27xUfi67tUd5
Learning is on by default once a principal store exists. After every turn, its on_turn_end hook records corrections from the chat, and that loaded the whole session to keep its last 12 messages. A review loaded the whole session to keep its last 6 for its digest. So even with the loop's own count and tail in SQL, each turn still decoded every message of its session once. Learner.last_messages reads the newest rows through the session store's last_messages, the same helper the loop uses. A store without that helper gets the old full read and its tail, so results do not change. The chat capture and the review digest use it. The new test runs both on a 302-message thread whose last message is a correction. The capture records the same verdict after decoding at most 12 messages, and the digest decodes at most 6. Main decoded all 302 each time. User guide: none. Developer guide: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QDoXr7oqhY27xUfi67tUd5
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
abu-aska
left a comment
There was a problem hiding this comment.
Verdict: approve. Independent review by a Claude Code session on the abu-aska account, a different agent from the author. Reviewed at 55f35930. Tests and probes run, every finding re-checked.
What works
- Same results as main. I built one store on main through the public API: 3 sessions of 1,300 messages (plain, thread, private) with notes and undone turns, plus 3,500 events across 3 sessions and no session. Main's full reads and the head's
user_turns,last_messagesanditer_eventsgave 237 digest lines, andcmpprinted IDENTICAL.- That covers 216 event reads (135,808 events):
sincefrom 0 to 9,999 across page edges, each session andNone,with_globalon and off, andskipof(),message.deltaandnotice. - It also covers tails of 1, 6, 12, 40, 999 and 5,000 messages, and the turn counts (358, 350, 342).
- That covers 216 event reads (135,808 events):
- Turn count rule. Over 15 note values (missing,
None,"",0,0.0,False,[],{},"threads",True,[0],{"a": 1},1e-400, NaN, inf),user_turnsequals main's Python count for every value except NaN (see Nits). - Forks are faster and leave nothing on failure. Fork times, main against head:
- Plain session, 5,000 messages: 3.90 s and 1.29 s.
- Agent thread, 20,000 messages with 20 KB tool results: 20.77 s and 9.15 s.
- Agent thread, 50,000 messages: 32.19 s and 4.40 s.
- A fork that runs out of pages (
PRAGMA max_page_count): main leaves 1 child with 94 copies. The head leaves 0 children and 0 copies, andintegrity_checkis ok.
- A second probe with fixed ids made 26 forks (812 messages, 769 search rows, 87 summaries) and found the main and head tables byte-identical.
- The stdio typed reply holds when the first page fails. With an undecodable row at seq 500, both trees send
c1aninternalreply and answer the next command. - The new cleanup fixes a queue left on main. Main's SSE subscribe left 1 queue when its first read failed. The head leaves 0.
- The paging tests have teeth. Two in-memory mutants were caught:
SqliteLog.readput back to one unbounded read fails 2 tests, and the union page without its outerLIMITfails 1. - CI: all 10 check runs succeed on
55f35930.
Should fix
1. A large fork holds the write lock for its whole run, so another process fails with database is locked.
- Repro:
scripts/lockhold.pyforks in one process. A second process pollsBEGIN IMMEDIATEand opens aSessionStore1 s after the fork starts. The parents were built through the public API.- Plain session, 20,000 messages, 4,995 summaries. Head: fork 17.48 s, no write lock for 17.29 s, and the second open failed after 5.02 s with
OperationalError: database is locked. Main: fork 31.05 s, longest wait 0.75 s, and the open succeeded after 0.03 s. - Agent thread, 20,000 messages with 20 KB tool results. Head: fork 9.15 s, no write lock for 7.19 s, and the open failed after 5.01 s. Main: longest wait 0.41 s, and the open succeeded after 0.13 s.
- Agent thread, 50,000 messages. Head: no write lock for 3.96 s, and the open waited 2.94 s before it succeeded. Main: the open succeeded after 0.00 s.
- Plain session, 20,000 messages, 4,995 summaries. Head: fork 17.48 s, no write lock for 17.29 s, and the second open failed after 5.02 s with
- Cause: all of
forkruns inside_tx'sBEGIN IMMEDIATE. That includes reading and re-encoding every row and the correlated summaries query. On the 20,000-message plain session, that query alone took 14.68 s of the transaction._openkeeps Python's default 5 s busy timeout, so other seats on the same home and CLI commands give up. - Fix:
- Read the rows, build the copies and select the summaries before
BEGIN IMMEDIATE, for example in a_readsnapshot. Inside the write transaction, check that the parent's rows up touptoare unchanged, then insert. - Make the summaries selection one pass: find the first hidden or missing seq once, then take the summaries that end before it.
- Add a test that a second
SessionStoreopens during a fork of a few thousand messages.
- Read the rows, build the copies and select the summaries before
2. A replay read that fails after the first page leaves a stdio client subscribed and silent.
- Repro:
scripts/stdio_badrow.pybuilds 3,000 events, sets the body of seq 1,500 to{}, and runsserve_lines: subscribe since 0, a live publish,session.list, then EOF.- Main:
c1getsinternalwithValueError: Notice: Notice.__init__() missing 1 required positional argument.c2gets its reply. - Head:
c1getssubscribed: true, then 1,000 events (last seq 1,000). The live event never arrives, andserve_linesraisesValueErrorfrom its EOF flush.
- Main:
- A bare
Subscriptionthat catches the error and callsnext()again skips the other 1,999 backlog events and returns live seq 3,001. A finished generator reads as an empty backlog. No consumer in the tree retries today. - Cause: only the first page is read at subscribe. A later page fails inside the
pumptask, which closes its queue and sends nothing. - Fix: in
pump, catchExceptionand send a typed failure for the subscribe, or a notice, before ending. Guard the EOF flush the same way. InSubscription.next, when the backlog raises, drop the queue and keep raising, or end the stream withClosedso the client resumes withsince. Add a test with an undecodable row on page 2.
3. The tests do not pin two of the claimed properties.
- I ran in-memory mutants as pytest plugins against the three
tests/core/*_254.pyfiles,tests/learn/test_learn_signals.pyandtests/trace. Each mutant below passes them all (146 passed, 2 xfailed):forkwrites its summaries after the transaction, as autocommit statements.test_a_failed_fork_leaves_nothingfails at the 30th copy, before any copy is inserted, so it rolls back only the session row.iter_eventsappliesskipto the first page only. Trace's turn-end read passesskipto drop the delta and tool-output events on every page.
- A third mutant, the union page without its outer
LIMIT, is caught only by the cost test, through itslen(...) == 10check. - Fix: make a fork fail at its last write (for example a TEMP trigger that raises on
INSERT INTO summaries) and check all four counts. Add an equivalence case with mixed event types and askipthat spans pages. Add a case where both union branches hold more than one page.
Nits
- A NaN note counts as a turn.
json.dumpswrites NaN as a bareNaN, and SQLite'sjson_extractreads it as null. Souser_turnsgives 2 where main's count gives 1 (scripts/notes.py). Nothing writes a note other than"threads"or"private"today. Name the NaN case in theuser_turnsdocstring and in the PR body's statement of the rule. - A fork on a full disk now reports the wrong error.
scripts/diskfull.pyon the head raisescannot rollback - no transaction is active, withdatabase or disk is fullonly as its context. Main raised the disk-full error itself. SQLite has already rolled back, and_txrunsROLLBACKanyway. Roll back onlyif self._db.in_transaction, as__init__does. The data is clean. - stdio subscribe registers its queue before the reply write. If that write raises (
BrokenPipeError), the queue stays in the hub: 1 queue on the head, 0 on main (scripts/stdio_gone.py).MAX_LAGdrops it later, and the stdio core exits on that error anyway. Start the pump before the reply, or closesubwhen the write fails. iter_eventsdoes not checkpage.page=0raisesIndexErroron the firstnext.page=-1reads all 25 events in one page, then raisesIndexError. No caller passespage. RaiseValueErroraslast_messagesdoes for its limit.- Docs and PR body:
docs/OPTIMIZATION.mdrow #254 citestrace.py:540anddiagnostics.py:155. The calls are attrace.py:541anddiagnostics.py:154. Naming the functions would not drift.- The D-010 amendment's Tests list leaves out
tests/learn/test_learn_signals.py, the only test of theLearner.last_messageschange. Thedocs/DOCS-MAP.mdrow names 5 of the 9 changedsrcfiles. It leaves outcore/engine.py,core/trace.py,diagnostics.py,learn/review.pyandlearn/signals.py. - The PR body says
SqliteLog.readundone fails 1 test. It fails 2 (test_subscribe_from_zero_holds_one_pageand the stdio test).
Notes
- Peak memory of a large fork is higher. On the 20,000-message agent thread with 100 MB of message data, the fork grew peak RSS by 629 MB on the head and 401 MB on main. Both load the whole range. Reading in pages inside the transaction would bound it.
- Undo and the turn count use different rules (already on main).
undotreats a note of""as a note (IS NULL). The count treats it as a turn.undo(1)on ask, reply, empty-note, reply removes 3 rows on both trees, and the count goes from 2 to 1. - A subscriber mid-replay at shutdown reads the store after
engine.close().serve()closes the hub, then the engine, then the servers. On the head, the later backlog pages read SQLite.scripts/shutdown.py: the file store reopens its connection ("open again after close: True"). A:memory:store raisesProgrammingErrorafter 1,000 events. Main delivers all 2,500 from memory on both.- Production uses the file store, and the process exits next.
Checks
python -c 'import exo; print(exo.__file__)'under each tree'sPYTHONPATH:.../main/src/exo/__init__.pyand.../w1102/src/exo/__init__.py. SQLite 3.45.1.pytest -q -p no:cacheprovider tests/core/test_session_hot_paths_254.py tests/core/test_fork_one_transaction_254.py tests/core/test_event_paging_254.py tests/learn/test_learn_signals.py tests/learn/test_learn_review.py tests/protocol tests/traceon the head: 314 passed, 2 xfailed in 49.45 s.pytest -q -p no:cacheprovider tests/core tests/learn tests/docson the head: 1423 passed, 2 skipped in 135.27 s.- Mutants (
pytest -p <plugin>) on the threetests/core/*_254.pyfiles,tests/learn/test_learn_signals.pyandtests/trace: fork summaries after the transaction 146 passed, 2 xfailed.skipon the first page only 146 passed, 2 xfailed. No outerLIMIT1 failed, 145 passed, 2 xfailed. - The
SqliteLog.readmutant on the three*_254.pyfiles and the learning test only: 2 failed, 48 passed. scripts/equiv.py: main and head digests identical (237 lines, 216 event reads, 135,808 events).scripts/notes.py: 1 difference in 15 note values (NaN).scripts/lockhold.py,scripts/forkmem.py,scripts/diskfull.py,scripts/stdio_badrow.py,scripts/stdio_gone.py,scripts/shutdown.pyandscripts/pagearg.pyon both trees: outputs as quoted above.- CI on
55f35930: 10 of 10 check runs succeed. - The
scripts/*.pyprobes are local to this review and not part of the repository. Each ran under each tree'sPYTHONPATHwith a fresh temporaryHOMEandEXO_HOME. The large parents were copied per run, so main and the head forked the same rows.
Generated by Claude Code
abu-aska
left a comment
There was a problem hiding this comment.
Verified
user_turnsSQL matches the old Python rule across the falsy/truthy cases: missing, null, false, 0, 0.0 and "" count; a non-empty note does not. The string "[]" is not confused with the JSON array []: the array/object arm requires json_type to be array or object, so a string "[]" still does not count, while a real [] or {} does. The new tests pin exactly these values, plus an undone tail.last_messagesreads only the newest rows through the (session, seq) index and returns them in transcript order;messages()on main already filters hidden=0, so the hidden=0 filter matches the old reads.- Fork rewrite keeps the old behaviour: hidden rows are excluded by both the old
messages()call and the new query, copies are renumbered 1..n, agent-log pos stays unset for fork copies (meta local=fork), and the summaries copy uses the same end_seq rule. Atomicity holds:copyruns inside_tx(BEGIN IMMEDIATE, ROLLBACK on any exception), and the session row, message copies, FTS rows and summaries commit together. iter_eventspages at 1,000 and stops at the newest seq at call time, so a long read holds one page; the with_global UNION ALL takes the top page of each stream before merging, which cannot drop or repeat a seq.- Server side:
Subscriptionstill registers its queue before the backlog is read, and__anext__closes the queue when the stream ends for lag, so the newpumpresubscribe does not leak queues. Thedispatch/decodesplit preserves the old failure shape (None, typed failure) for undecodable lines, and the stdio subscribe path still answers a badsincewith a typed reply instead of killing the feed. - Landing rules: CHANGELOG, DECISIONS (D-010 amendment) and DOCS-MAP updated in the same change, plus three new test files and the mypy baseline refreshed; types and lint pass.
Non-blocking notes
last_messages(limit=0)returns [] while the oldmessages()[-0:]slice would have returned everything. No caller passes 0 (40, 12, 6), so this does not block, but the helper's contract should stay "at most limit" rather than slice-like.- Issue #1103 (the one-shot
events.subscribereply) is deliberately left out of this PR and stays open; it needs a protocol decision, so it is not a gap in this change.
Verdict
Approve. The hot-path reads are equivalent to the old ones, the fork is now atomic without changing what it copies, and the paging is bounded as claimed.
|
This merged before the findings in review 5732419504 were fixed, so two of them are now on main. A large fork holds the write lock for its whole run, so another process that opens the store fails with "database is locked". A replay read that fails after its first page leaves a stdio subscriber subscribed and silent. I am fixing both in a follow-up PR from main, with the tests the review asked for, its nits, and the Generated by Claude Code |
Brings #1089 (the gate reads what printf or echo -e pipes into a shell, #1047) and #1102 (session hot paths read in SQL and pages, #254). GitHub reported a conflict in CHANGELOG.md, where those PRs and this branch each add lines at the top of Fixed. All lines are kept. Every other file merged on its own. Tests: tests/docs, tests/test_merge_attributes.py andntests/core/test_event_paging_254.py: 64 passed. test_browser_startup.pynand test_csp_web.py with headless Chromium 141: 32 passed. User guide impact: none. Developer guide impact: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SWwciAkq4F3SjfvXMYh8Lp
Brings #1089 (the gate reads what printf or echo -e pipes into a shell, #1047) and #1102 (session hot paths read in SQL and pages, #254). GitHub reported a conflict in CHANGELOG.md, where those PRs and this branch each add lines at the top of Fixed. All lines are kept. Every other file merged on its own. Tests: tests/docs, tests/test_merge_attributes.py andntests/core/test_event_paging_254.py: 64 passed.ntest_provider_retry_web.py with headless Chromium 141: 25 passed. User guide impact: none. Developer guide impact: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SWwciAkq4F3SjfvXMYh8Lp
Brings #1089 (the gate reads what printf or echo -e pipes into a shell, #1047) and #1102 (session hot paths read in SQL and pages, #254). GitHub reported a conflict in CHANGELOG.md, where #1089 and this branch each add a line at the top of Fixed. Both lines are kept. src/exo/gate.py, DECISIONS.md, docs/GATE.md and docs/DOCS-MAP.md merged on their own. The branch's gate.py diff against main has the same added and removed lines as 9bf1ba3 against 6ec085b. Tests: the #867 and #1047 gate test files, tests/docs and tests/test_merge_attributes.py: 453 passed. tests/security and tests/test_gate_diff.py: 17765 passed, 117 skipped, 36 xfailed. plugins/exo-gate: 2868 passed, 17 xfailed. gate_diff against main 53226fb, built-in --no-variants: 1,405,976 pairs, lowered 0, tightened 0, errors 0. Aimed --only-corpus: the #867 loop rows inside printf, printf %b, echo -e and sudo -s pipes, escaped and plain, 4,440 actions x 101 policies (the 88 built-in and 13 with /dev*, /proc* and *store* target rules) = 448,440 pairs, lowered 0, tightened 9,370, errors 0. An escaped loop pair piped through printf or echo -e now denies under deny: [target:/proc*] as the plain pair does, where main asks. ruff and git diff --check: clean. User guide impact: none. Developer guide impact: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SWwciAkq4F3SjfvXMYh8Lp
Main gained #1102 (sessions hot paths, #254) and #1106 (context build reads, #262) since this branch's base. Two docs files conflicted, and each side's text is kept whole: - DECISIONS.md: D-010 now ends with this branch's 2026-10-31 amendment (#263) and then main's 2026-11-01 amendment (#254), in date order. - docs/OPTIMIZATION.md: the #262 row is main's (#1106) and the #263 row is this branch's. Each side changed only its own row. CHANGELOG.md, docs/DOCS-MAP.md and src/exo/core/engine.py merged without a conflict. User guide impact: none. Developer guide impact: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QDoXr7oqhY27xUfi67tUd5
|
The follow-up is #1115, and issue #1114 records the two regressions it fixes. A fork now builds its copies on a read snapshot and holds the write lock for under 0.5 s, and a replay page that fails ends a stdio subscribe with a typed reply. It also has the tests review 5732419504 asked for, its nits, and the Generated by Claude Code |
Main adds #1089 (gate printf escapes), #1102 (session hot paths, #254), #1101 (Providers redraw in the web view), #1106 (each summary tree read once, #262), #1105 (one HTTP client per event loop, #263), #1107 (browser startup labels) and #1108 (tasks.list active filter, #997). src/exo/core/engine.py needed a hand resolution. This branch moved stop_channels into the close-step tuple. #1105 appended self.router.aclose to the same tuple. The tuple keeps both: stop_channels first and router.aclose last. So the router's HTTP clients close with the other transports, before the bounded wait for turns and tool workers. The other engine.py hunks from #1102 and #1108 merged on their own. src/exo/harness_runtime.py: #1108 makes the engine call agents.list(session, active=...), and the terminal now sends tasks.list with active set. DisabledDelegator.list did not take active, so with delegation off that command failed with a TypeError. It now takes active and still returns an empty list. tests/test_harness_runtime.py checks both the method and tasks.list through the dispatcher. Both checks fail without the fix. docs/HARNESS.md: step 2 of the shutdown order now says that close also closes the HTTP clients the model router made. User guide impact: none. Developer guide impact: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QDoXr7oqhY27xUfi67tUd5
This branch is stacked on #500. It takes #500's new head 73ff5a8, which merges main 21e964c (#1089, #1102, #1101, #1106, #1105, #1107 and #1108) on top of the 293e477 merge. No file needed a hand resolution here. - #500's head resolved src/exo/core/engine.py by hand. Its close-step tuple keeps stop_channels first and main's router.aclose last. It also lets DisabledDelegator.list take #1108's active argument. This branch changes neither file. - src/exo/gate.py merged on its own. #1089 adds a second reading of a call when a shell reads what printf or echo -e writes. This branch's te1: rule is its own branch of _classify_call for tool_output. It reads no shell line, so neither changes the other. - src/exo/core/sessions.py merged on its own. #1102 makes a fork one transaction and pages the event read. This branch changes update_meta, in other lines. The store's lock is reentrant, so this branch's metadata callback can still read the store. - src/exo/core/context.py merged on its own. #1106 reads each summary tree once per call. This branch changes one docstring there. Its EvidenceContext calls the wrapped context's build, and the tree does those reads inside its own build. - src/exo/core/agents/delegate.py merged on its own. #1108 changes list. This branch changes how a child's context is made. - DECISIONS.md, docs/DOCS-MAP.md, docs/DEVELOPER-GUIDE.md and CHANGELOG.md merged on their own. User guide impact: none. Developer guide impact: none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QDoXr7oqhY27xUfi67tUd5
Each turn decoded every message of its session twice, or three times with learning on. A fork wrote one transaction per copied message. The hub's replay,
exo traceand/handoffread the whole event log at once. Over stdio,events.subscribealso built a reply with every event and then dropped it.Now a turn counts and tails its session in SQL, a fork is one transaction, and event reads with no bound go 1,000 events at a time. Results are the same as before.
Part of #254 (W2-4). W1-5 landed in #442. What remains is the context transcript tail, which is draft #903. This branch carries the same
last_messageshelper as that draft, word for word and in the same place, so the two merge cleanly.Finding 1: a turn decoded its whole session twice
Loop._turnloaded the whole session to count the user turns it passes to memory, then loaded it all again to keep the last 40 messages for the memory checkpoint./handoffalso loaded the whole thread to count user turns. With learning on, which is the default once a principal store exists, the chat capture after each turn loaded the session a third time to keep its last 12 messages. A review loaded it for its last 6.SessionStore.user_turnscounts in SQL with the old rule: a user message counts unless its context note is one Python reads as true (a note of"",0,false,null,[]or{}still counts).SessionStore.last_messagesreads the newest rows through the(session, seq)index. The loop and/handoffuse them. Learning's chat capture and review digest read their tail throughLearner.last_messages, which uses the same helper.tests/core/test_session_hot_paths_254.py. Both helpers equal the full load on sessions with notes of every kind and an undone tail. A turn on a 1,300-message session decodes at most 45 messages, with the same turn number and checkpoint./handoffgives the same count without a whole-thread load.tests/learn/test_learn_signals.py. On a 302-message thread that ends with a correction, the capture records the same verdict after decoding at most 12 messages, and the digest decodes at most 6.Finding 2: a fork wrote one transaction per copy
SessionStore.forkwrote each copy throughappend_message, each in its own write transaction, and each summary in another statement.create_session. Every copy is built asappend_messagebuilt it, and the copies, search rows and summaries are written withexecutemany. A failure rolls it all back.tests/core/test_fork_one_transaction_254.py. The new fork equals the old one row by row (data bytes, seq,copy_pos, search text, summaries) for thread, scheduled and private parents, with and without a fork point. A fork is one transaction, and a failed fork leaves no row behind.Finding 3: event reads with no bound read the whole log
SqliteLog.read), trace and/handoffcalledevents_sincewith a limit of 2^30. ASubscriptionthen copied that list into its backlog.SessionStore.iter_eventsreads 1,000 events at a time and stops at the newest seq at the call, so it returns what one read at the call returned. It reads the first page at once, so a badsincestill fails when the caller asks. The three callers use it.Subscriptiontakes the log's iterator as its backlog through the newHub.replay, whichHub.sincealso lists. The queue is still registered before the backlog is read, so there is still no gap and no repeat. The one-shotevents.subscribereply still carries the whole replay, as the protocol says.with_global, the hub's replay) is now two index searches joined byUNION ALL. ItsORform sorted every later event on each call, so reading page by page would grow with the square of the log.tests/core/test_event_paging_254.py.iter_eventsequals one unbounded read for each filter. The replay test fromdocs/OPTIMIZATION.mdW2-4 subscribes from seq 0 across three pages while live events publish, and every seq arrives once, in order./handoffnever ask for more than one page. One page with global events costs the same at 2,000 events and at 20,000. A filter put inHub.replayreaches bothHub.sinceand a subscription's backlog.Finding 4: a stdio subscribe still read the whole log
Found while checking finding 3.
events.subscribethrough the dispatcher. Its one-shot reply decoded every event and made a dict of each. The transport then dropped that reply and streamed from aSubscription.Subscriptionat once. Asincethe log cannot read still gets the same typedinternalreply, and the transport lives on. ASubscriptionwhose first read fails now takes its queue back out of the hub, so no queue is left to fill with later events.tests/core/test_event_paging_254.py. A stdio subscribe from seq 0 sends its first event after one page is decoded, and every event arrives once, in order. Asincepast SQLite's range gets the typed reply and leaves no queue in the hub.Benchmarks
Local runs on the file store in WAL mode, from a script that is not part of the suite:
Each test fails without its fix
With the source of all seven commits undone at once (main 6ec085b's
srcwith this branch's tests), 14 of the 25 tests fail. The 11 that pass are the nine fork equivalence cases, the replay test and the stdio typed-reply test. Main already meets those: they check that the new code keeps main's results.Each part was also undone alone, with the tests kept:
/handoffcount)./handoffcount, the/handofftask events,SqliteLog.read, aSubscriptionthat lists its whole backlog, and theORform of the global page each fail 1 test. Trace fails 2.Subscriptioncleanup undone: the typed-reply test fails, because a queue is left in the hub.Hub.replay: the new replay test fails, because the backlog skips the filter thatHub.sinceapplies.The equivalence tests and the replay test pass on the old code too, as they should.
Overlap with open PRs
Checked by trial merges without the CHANGELOG union driver, on the PR heads as of 2026-11-02 03:20 UTC.
Hub.since. TheirSubscriptiontakes its backlog fromHub.since. HereHub.sincelistsHub.replay, and everySubscriptiontakes its backlog fromHub.replay. The two conflict on thetypingimport and onHub.since.Hub.replay. Thensinceand every subscription both apply it. A filter kept only inHub.sincewould not reach a subscription's backlog. TheHub.replaycommit here makes this conflict show up at that line. Before it, the backlog read the log directly, and the merge would have dropped the filter from the backlog with only an import-line conflict.last_messagesand uses it there.sessions.pymerges cleanly in either order. Its CHANGELOG conflict with main is its own.Loop._turn, so it conflicts on the two loop lines changed here. Whichever lands second keeps the other's line.latest_model_call_reasoningtoSessionStoreright whereiter_eventsgoes. Keep both methods. These PRs already conflict with main in many files.loop.pyorsessions.py. Their conflicts with this branch are the ones they already have with main.Checks (local)
On 55f3593 (main 6ec085b), with the worktree's
srcfirst on the path and a temporaryHOMEandEXO_HOME:tests/security/test_gate_sudo_shell_stdin.py, and a YAML flow value passed the 5 s cap intests/security/test_gate_yaml_progress_981.py. Run again on the same head, both files pass (313 passed). This branch does not touch the gate.tests/core/*_254.pyfiles andtests/learn/test_learn_signals.py): 50 passed.tests/protocol,tests/trace,tests/learn, the jobs and seat tests, and two security files): 502 passed, 2 xfailed.tests/docs: 49 passed. The core budget test passes.wait_forargument type inSubscription.next, is pruned from the baseline, which has one entry fewer than main's.Core lines
The branch counts 16,122 core lines, 1,309 above the floor of 14,813. That is 86 more than main's 16,036:
sessions.pygrows by 63,server/app.pyby 12,server/engine.pyby 10, andtrace.pyby 1. D-083 sets no ceiling, so nothing else changes. The structure caps hold: 39 of 39 inward imports and 8 of 8 private-state reads.User guide: none. Developer guide: none.
Generated by Claude Code