Skip to content

#1057 Release closed sessions' transcripts on both platforms - #1060

Merged
ivanfenenko merged 7 commits into
mainfrom
fix/1057-release-closed-sessions
Nov 16, 2026
Merged

ivanfenenko merged 7 commits into
mainfrom
fix/1057-release-closed-sessions

Conversation

@ivanfenenko

@ivanfenenko ivanfenenko commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #1057: the three items about releasing closed sessions' transcripts. The diff view, Changes and File Viewer items are handled separately.

Builds on #1051 (merged); this branch is merged with main.

Problem

Device check of #1051 on an Android emulator with a 192 MB Java heap: after opening and closing 10 heavy child sessions, 94 MB stays live. About 75 MB of that is tool input strings that the message store holds for the parent and the 10 children. With the heap in that state, opening two more heavy screens ran the app out of memory.

On Android, closing a session's screen never released its transcript. Each observeMessages shareIn (replay 1) kept its share coroutine and replay buffer alive in the app-lived scope. That is also why clearCache() freed nothing. iOS also kept each closed session's store, last frame and history window, plus up to 8 sessions of prepared history (capped by text length only, not tool output).

Policy (same on both platforms)

TranscriptRetentionPolicy (Android domain/message/store/TranscriptRetentionPolicy.kt, iOS Domain/Message/Store/TranscriptRetentionPolicy.swift):

  • CLOSED_SESSION_GRACE_MS / closedSessionGraceMs = 120 000 (2 minutes)
  • MAX_WARM_CLOSED_SESSIONS / maxWarmClosedSessions = 3

A session stays loaded while anything observes it. That covers its Session Chat anywhere on the back stack, a tool-group screen, and a parent's activity card watching a running child. All of these read the same observeMessages stream. When the last observer stops, the session stays warm for the grace period, and only the 3 most recently closed sessions stay warm; older closed sessions are released at once. On memory pressure (Android onTrimMemory at the levels the highlighter already trims on, and onLowMemory; iOS memory warning) every closed session is released at once and open sessions are left alone.

Mechanism

  • Android: MessageSync reference-counts collectors per session. Each session's shareIn now runs in its own child scope, so a release cancels the share coroutine (which frees the replay buffer) and then drops the last frame, identity, history window, health and the cache handle. The store side is InMemoryMessageStore.release(slot), which drops base messages, parts, raw infos, orders, revisions, delta chunks and running context. clearCache() also cancels every share scope. TranscriptMemoryPressureObserver is registered from OpenCodeMobileApplication, the same way as the TextMate trim observer.
  • iOS: MessageSync counts observers when the stream is created and in onTermination. A release calls finish() on the session's SharedLiveObservation, which cancels the upstream and clears its last value, drops the same per-slot state, and calls InMemoryMessageStore.release(sessionID:). DisplayMessagePipeline drops the session's prepared history when its transcript is released. Its existing memory-warning observer now also calls releaseClosedSessions().
  • Late REST commits: a message loop that was stopped or released can no longer commit a late REST page. On Android this is an isActive guard on the coordinator loader and the split-turn backfill. On iOS each loop gets a run token, checked before a commit or publish.
  • Opening during a release: on Android, an observation that opens while its previous one is still releasing waits for that release to finish and skips the stale snapshot. On iOS the release is synchronous.

Live events for a released session

Both platforms apply transcript events only inside an active observation's message loop. That holds for v1 /global/event and instance /event and for v2 /api/event, which all feed the same foreground stream. Once a session is released, its events are dropped, the same as for a session that was never opened. They do not rebuild a partial transcript. Home status, permissions and questions live in their own stores, which keep their own subscriptions and keep updating (there is a test for this on each platform).

Re-entry

A released session opens exactly like a first open: it paints from the session cache, then confirms or replaces that paint from REST. Within the grace period it still paints the held transcript at once, as before.

Checks

  • Android: ./gradlew :app:testDebugUnitTest (3405 tests, 0 failures), :app:assembleDebug, :app:assembleDebugAndroidTest. ktlintCheck reports nothing in the changed files.
  • iOS: xcodebuild build and build-for-testing for generic/platform=iOS Simulator (OpenCode Mobile), plus build for Hex Code. The new iOS tests were compiled but not run: no simulator was available.
  • New tests, the same cases on both platforms (Android MessageSyncTranscriptReleaseTest, iOS MessageSyncTranscriptReleaseTests, plus one status-store test each). The grace period runs on virtual time on Android and on a manual sleeper on iOS. The cases:
    • release after the grace period
    • the warm cap, with 4 closed sessions
    • a session kept by a back-stack chat, a tool group or an activity card
    • a parent's activity card keeping a child
    • re-open after release: cache paint first, same transcript, same update sequence as the first open
    • re-open within the grace period
    • clearCache() with open and closed sessions
    • memory pressure
    • events after release
    • re-open while a release is in flight
  • Four existing Android load-older tests used observeMessages(...).first() and then loaded older pages on a session nothing observed any more. They now keep the screen open while loading, as the app does.
  • No UI change, except that returning to a session left more than 2 minutes ago (or one of the oldest of several closed ones) repaints from the session cache and then refreshes, instead of painting the held transcript at once. Screenshots: not applicable; device verification follows.

Risks / Follow-ups

Device checks still needed:

  • Heap on the low-heap Android emulator before and after visiting 10 heavy child sessions. Expect it to return close to the earlier level.
  • Re-entry into a released session with and without network.
  • A running session left and re-entered after release.
  • Home status, permission and question indicators for a released session.
  • iOS memory for the same steps.
  • The iOS tests need a simulator run.

Other notes:

  • Android also releases closed sessions on TRIM_MEMORY_UI_HIDDEN, when the app goes to the background, because that level already counts as Moderate pressure for the highlighter.
  • I did not prove with a GC probe that the released transcript objects are unreachable. The tests check that the store, the sync maps and the share or observation entry are empty.

🤖 Generated with Claude Code


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.


Note

Medium Risk
Touches core message sync, caching, and memory lifecycle; wrong retention could drop live data or cause extra reloads, but open sessions and explicit guards limit exposure.

Overview
Adds transcript retention and release on Android and iOS so closed sessions stop holding large in-memory message state (tool inputs, share/replay buffers, prepared history).

Shared policy (TranscriptRetentionPolicy): transcripts stay while any UI still observes observeMessages; after the last observer leaves, the 3 most recently closed sessions stay warm for 2 minutes, older closed sessions drop immediately; memory pressure releases all closed sessions at once.

MessageSync now reference-counts observers per session, cancels per-session share/observation scopes on release, and clears sync maps plus InMemoryMessageStore.release / engine state. Late REST commits are blocked once an observation is released (mayCommit / run tokens). Re-opening a released session behaves like a first open (cache paint then server); reopen within grace still paints the held transcript.

Android: TranscriptMemoryPressureObserver registered from the application class (trim levels aligned with TextMate). iOS: DisplayMessagePipeline evicts prepared history on transcript release and calls releaseClosedSessions() on memory warning.

Wide mirror tests on both platforms; some older Android tests now keep an active observer while loading older pages.

Reviewed by Cursor Bugbot for commit 0b3924b. Bugbot is set up for automated code reviews on this repo. Configure here.

ivanfenenko and others added 6 commits November 15, 2026 20:57
… cache flushes

Session Chat ran out of memory on Android with long sessions. Three causes:

- Every timeline projection built a per-line inspector body for every tool
  card and copied each output into the card. Cards now keep only what the
  collapsed row draws and a flag; the detail (body and inspector) is built
  from the tool part when it opens. A write's +N is counted, not split.
- The tool group navigation key carried every member's output and inspector
  lines, and Navigation3 prints and saves the key. It now names the members
  by block id; the route reads them from the message store.
- The session cache encoded the whole transcript into one string and
  swallowed the OutOfMemoryError. It now encodes one message at a time and
  keeps the newest whole messages within about 2 MB; Errors propagate.

iOS: the tool card keeps the classifier inputs (shared string storage) and
classifies on open; the write line count no longer splits; the cache encode
uses the same per-message budget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Android's cursor window holds 2 MB, so a session cache row larger than
that throws SQLiteBlobTooBigException on read. Earlier builds wrote
whole transcripts (4.3 MB for a heavy session), and commit and retain
read the existing row first, so that row could never be replaced and
the session never painted from cache again.

- commit and retain read only the row's retain time and payload size.
- load skips a row over the window instead of throwing.
- The message timeline budget counts UTF-8 bytes, as SQLite stores
  them and as iOS already does, and stays under the window (1.8 MB).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
OpenCode emits each tool step as its own assistant message, and the
timeline merges a run of them into one group under one message id. The
route looked members up only in that message, so a 78-tool group opened
with one member. Look each member up by block id across the transcript.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A seed is only a first paint, but on Android an OutOfMemoryError from
decoding an oversized legacy timeline row escaped seed() and aborted
observeMessages before the live load ran.

- seed() loads and decodes in a helper and reads any failure, including
  OutOfMemoryError and StackOverflowError, as a miss. The row and the
  decode's allocations are unreachable by the time it logs.
- observeMessages guards seed() the same way, so no cache failure stops
  ensureFresh.
- encodeMessages no longer always keeps the newest message: a message
  whose text alone is over the remaining budget is not encoded at all,
  and when the newest does not fit the timeline keeps none (a seed miss).
  One huge tool output no longer builds its whole JSON string for a row
  Android could not read back.
- iOS: the pipeline characterization test waits longer for the first
  frame and no longer indexes emissions it may not have, so a slow
  runner fails the expectation instead of crashing the test host.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A session's in-memory transcript (messages, parts, raw info, last published
frame, history window, shared-flow replay and its share coroutine) is now
reference-counted on the store observation. Once nothing observes it, the
three most recently closed sessions stay warm for two minutes and the rest
are released (TranscriptRetentionPolicy, same names and values on Android
and iOS). Memory pressure (Android onTrimMemory/onLowMemory, iOS memory
warning) releases every closed session at once, and clearCache() now stops
the share coroutines so nothing stays reachable through a replay buffer.

A released session re-opens like a first open: session cache paint, then
the server. A loop that was stopped or released can no longer commit a
late REST page. On iOS a release also drops the session's prepared history.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Base automatically changed from fix/1033-session-chat-memory to main November 16, 2026 00:55
…ed-sessions

# Conflicts:
#	android/app/src/main/java/dev/opencode/mobile/domain/message/store/MessageSync.kt
#	android/app/src/main/java/dev/opencode/mobile/domain/sessioncache/SessionCacheCodec.kt
#	android/app/src/main/java/dev/opencode/mobile/ui/sessionchat/SessionToolGroupViewModel.kt
#	android/app/src/test/java/dev/opencode/mobile/domain/sessioncache/SessionCacheMessageBudgetTest.kt
#	android/app/src/test/java/dev/opencode/mobile/ui/sessionchat/SessionToolGroupRouteTest.kt
#	ios/OpenCode Mobile/OpenCode Mobile/Domain/SessionCache/SessionCacheCodec.swift
#	ios/OpenCode Mobile/OpenCode MobileTests/Domain/SessionCache/SessionCacheMessageBudgetTests.swift
@ivanfenenko
ivanfenenko marked this pull request as ready for review November 16, 2026 07:42

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review: no finding that 2+ of 2 passes agreed on.

5 finding(s) from a single pass, not posted
  • android/app/src/main/java/dev/opencode/mobile/domain/message/store/MessageSync.kt:254 high: Late loadOlder commits after dropSession and resurrects released transcript (muse-spark-1.3-contributor)
  • ios/OpenCode Mobile/OpenCode Mobile/Domain/Message/Store/MessageSync.swift:253 high: Late loadOlder commits after releaseTranscript and resurrects released transcript (muse-spark-1.3-contributor)
  • ios/OpenCode Mobile/OpenCode Mobile/Domain/Message/Store/MessageSync.swift:151 medium: Reopen during release runs two message loops that both apply the same live delta (muse-spark-1.3-contributor)
  • android/app/src/main/java/dev/opencode/mobile/domain/message/store/MessageSync.kt:992 medium: Split-turn backfill checks stillCurrent before the fetch, then commits into a released session (deepseek-v4.1-flash)
  • ios/OpenCode Mobile/OpenCode Mobile/Domain/Message/Store/MessageSync.swift:283 medium: Release drops MessageSync state under lock but clears the store after unlocking, racing a reopen (deepseek-v4.1-flash)

opencode pr-review · passes: muse-spark-1.3-contributor, glm-5.3-flash, deepseek-v4.1-flash · $0.115 · 1 pass(es) failed

@ivanfenenko

Copy link
Copy Markdown
Collaborator Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 3 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 0b3924b. Configure here.

@ivanfenenko
ivanfenenko added this pull request to the merge queue Nov 16, 2026
Merged via the queue into main with commit 242713c Nov 16, 2026
@ivanfenenko
ivanfenenko deleted the fix/1057-release-closed-sessions branch November 16, 2026 09:17
@ivanfenenko

Copy link
Copy Markdown
Collaborator Author

Device check (#1057, combined with #1061)

Real apps against the scenario harness on a v2 server only (opencode 2.2.5; no v1 binary on the machine, so only /api/event was exercised). Build: a local, unpushed merge of this branch (0b3924b6e) with #1061 (e021cdedb) and main (fffcf1d3c); no conflicts. Android: emulator, API 37, Java heap limit 192 MB, with a local heap sampler (500 ms) and a local log line in dropSession, neither committed. iOS: simulator, iOS 27.2.

Sessions: oom-l2, the same generator as the earlier oom-l (117 messages, 10 subagent children with 1 MB write inputs), but with the subagent calls at the end of the turn so the parent's newest-steps group links to them.

Android heap

Step #1051 build (earlier evidence) This PR + #1061
Parent open, peak 64 MB 63 MB
Parent settled, live after GC 34 MB 33 MB
Open and close the 10 children, peak n/a 94 MB
Right after the 10th child closes, live after GC 94 MB 46 MB (3 closed children still warm)
After the 2-minute grace period, live after GC n/a 38 MB
Then Changes, 67 files, +650,761 lines: peak / live after GC led to the crash 94 MB / 46 MB, no crash

Release timing, from the log line: from the 4th closed child on, each close released the oldest warm child at once (cap of 3). The last 3 were released exactly 120 s after each one closed. The parent stayed open throughout (more than 12 minutes, with children opened on top of it) and was never released. A closed session was released when the app went to the launcher (TRIM_MEMORY_UI_HIDDEN).

Behaviour

Check Android iOS
Re-enter after release: cached paint, then server, no blank timeline not checked (see below) pass
Running turn, left and re-entered after release not checked pass, with the note below
Released session's status on Home not checked pass: Running while released, then Done
Session left open past 2 minutes is not released pass (log: parent never released while open) not checked

Note for the running turn (v2): the server returns an empty text part for a step that is still streaming. So on re-entry after release, the reply shows only the cached paint plus what streams after re-entry (screenshot 3 shows "Progress 2 of 8." while the server was at 6). When the step finished, the text was complete and in order, with nothing duplicated (screenshot 4). This matches "re-enter = first open", but on main the held transcript would have kept the full live text.

Not checked: Android re-entry, Android running-turn re-entry and Android Home status. The device tool kept refusing touch injection on the emulator after a reinstall. Also not checked: offline re-entry, the tool-group and activity-card keep-alive, and the iOS memory warning, which were dropped from scope (they are unit-tested).

iOS
Running, before leaving
Home while released (2 min 8 s later)
Re-entry, first frame
Turn finished

Tests

CI android-checks and ios-checks pass on 0b3924b6e. Locally on the combined merge: Android :app:testDebugUnitTest (3,465 tests, 0 failures, including MessageSyncTranscriptReleaseTest 10/10 and SessionStatusLiveStoreTest 30/30). iOS, 23 suites run with -only-testing: MessageSyncTranscriptReleaseTests, SessionStatusLiveStoreTests and the Session Chat, message pipeline and sync suites all pass. FilesViewModelTests.aFinishedPassReleasesItsHighlightCoreSession (an existing test) failed once at load average ~100 and passed 3 of 3 alone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant