Skip to content

feat: idle session compaction before prompt-cache expiry - #64039

Closed
tiomat wants to merge 7 commits into
anomalyco:devfrom
tiomat:idle-compaction
Closed

tiomat wants to merge 7 commits into
anomalyco:devfrom
tiomat:idle-compaction

Conversation

@tiomat

@tiomat tiomat commented Nov 15, 2026 •

Copy link
Copy Markdown

Summary

Idle session compaction: open sessions compact shortly before their provider prompt cache expires, so returning after a break pays only for a short summary instead of reprocessing the full history at full input price and latency.

Design record: specs/v2/idle-compaction.md — independently reviewed (two rounds; presence leases instead of client liveness, anchor-based timers, delivery-time re-checks, manual-never-absorbed).

Flag: idle_compaction guards the whole behavior (off in releases). Tuning: compaction.idle.min_tokens (default 50,000).

Server side

  • Presence leases — POST /api/experimental/session/presence (Session.PresenceReport { client, sessions }). Process-local, ephemeral registry; a lease means "open in a tab", survives frozen/evicted PWA clients, expires after 2h, never written to the event journal.
  • Scheduler — per-session fiber map (the warming pattern), armed from the durable cache anchor on terminal executions and presence registration; fires at anchor + TTL − 90s. Firing laws: live lease, idle/settled session, warm anchor (TTL − 30s), size floor, once per idle epoch (completed or failed), no subagents/native-compaction/warming-configured/implicit-cache models.
  • Delivery — idle inbox control items (reason: "idle", delivery queue, epoch anchor in payload) re-check every law before Compaction.Started; stale items are consumed with InboxDelivered alone (returning steer, stranded-after-restart, cold cache). Manual /compact cancels a pending idle item and runs as manual steer.
  • Reason "idle" through compaction events/messages; ACP maps it to auto at the boundary (external vocabulary unchanged). Config compaction.idle.min_tokens, SDK regenerated.

Client side

  • @opencode/client/solid: createPresenceReporter (pure logic: report on set change, reset on disconnect, heartbeat lease refresh, best-effort error swallowing) + createPresence (thin Solid wiring).
  • App/desktop: createServerPresence per server controller — reports sessionId + routeSessionId of open session tabs plus the preview tab; per-tab/window client id in sessionStorage (a shared id would let windows overwrite each other's sets); uuid() from @opencode/util/uuid for insecure origins.
  • TUI: reports open tabs plus the viewed session (also when tabs are disabled); one crypto.randomUUID() identity per process.
  • Marker labeling: reason idle renders "Session compacted while idle" (app/session-ui, new English i18n key only) and "Idle compaction" (TUI); idle markers stay visible under background compaction like manual ones.

Reporting is always-on and cheap (one POST per minute per server); the server decides eligibility. Older servers without the endpoint: failures are swallowed. No exit beacon — closed tabs drop out on the next report, dead clients' leases expire (per the ADR).

Follow-ups

  • Held-precompute application scenario from the ADR verification list (needs a dedicated harness).
  • Graduate the flag and mark the ADR accepted once proven.

Testing (TDD)

40 new scenarios, written before the implementation:

  • session-presence.test.ts (5): lease replacement, multi-client union, expiry/refresh, unknown/archived ignored, no durable events.
  • session-idle-compaction.test.ts (19): fire timing under TestClock, arming/cancellation, shutdown exclusion, every firing law, 1h TTL, restart re-arm.
  • session-runner.test.ts delivery block (6): fresh idle delivery, stale epoch, cold anchor, returning steer, manual-cancels-idle, failed compaction terminal for the epoch.
  • server/test/session-presence.test.ts (2), ACP idle→auto wire test (1), solid-presence.test.ts (7): dedup, change, reconnect, heartbeat, disconnected silence, failure swallowing, dispose.

Stability: --rerun-each 10 --randomize → 2700/2700 across the runner and scheduler files; client reporter 70/70 rerun; app unit 2582/2582, TUI session-tabs 24/24, session-ui 562/562, ui 620/620, server 124/124, schema 92/92; full bun run check green.

Two latent bugs surfaced and fixed along the way: a mutex deadlock in the inbox cancel path (cancel re-acquired the session lock held by admission) and type-level escape hatches hidden by the old empty CompactionPayload.


Added by the opencode bot (AI-generated).

Public API: adds createPresenceReporter/createPresence to @opencode/client/solid and the ui.messagePart.compaction.idle i18n key (additive)

@github-actions github-actions Bot added the needs:compliance This means the issue will auto-close after 2 hours. label Nov 15, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This PR doesn't fully meet our contributing guidelines and PR template.

What needs to be fixed:

  • PR description is missing required template sections. Please use the PR template.

Please edit this PR description to address the above within 72 hours, or it will be automatically closed.

If you believe this was flagged incorrectly, please let a maintainer know.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The design holds up and everything new is behind idle_compaction. With the flag off, the scheduler and the runner's delivery re-check both return after the flag check. The changes to the inbox cancel path keep the same behaviour as before (lock, then mapping of conflict defects). Manual /compact now replaces a pending idle item, and a pending manual item absorbs an incoming idle one. I ran the new core, server and ACP tests (all pass) and called the new endpoint on a dev server (204 for a valid report, 400 for a bad payload). I couldn't watch an idle compaction fire end to end: it needs a real provider with an explicit cache.ttl, and no client reports presence yet. The type check couldn't run in this environment.

Public API (additive, backwards compatible for existing callers and configs):

  • New endpoint POST /api/experimental/session/presence (experimental.session.presence) with payload Session.PresenceReport { client, sessions }, plus the regenerated SDK method.
  • New config key compaction.idle.min_tokens and new flag idle_compaction.
  • SessionEvent.Compaction.* and SessionMessage.Compaction* reason: "auto" | "manual" → "auto" | "manual" | "idle". Typed SDK consumers that switch on reason exhaustively will now see a third value. Older clients reading a journal with idle compactions would fail to decode them, which only happens once the flag is on. ACP maps idle to auto. session-ui hides it like an automatic marker when background compaction is on.
  • Session.Inbox.CompactionPayload: {} → { reason?, idle? } (optional fields).

Concerns:

  • Every presence report re-runs the full eligibility check for every reported session and re-arms each timer. See the inline comment.
  • session-idle-compaction.test.ts changes module-level let fixtures (modelCache, nativeCompaction, resolveError, autoEnabled) across tests. That works today, but it breaks under concurrent tests or a test that forgets to reset them. Scoping them per test, or resetting them in one place, would make the 468-line file easier to follow.
  • The feature only fires for models with an explicit cache.ttl and no warming configured. That is intended per the ADR, but worth stating in the flag description so users know why it never fires.

"session.presence",
Effect.fn(function* (ctx) {
const dropped = yield* presence.report({ client: ctx.payload.client, sessions: ctx.payload.sessions })
yield* Effect.forEach(ctx.payload.sessions, (sessionID) => idle.touch(sessionID), { discard: true })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Every report runs idle.touch one session at a time for every open tab, and the HTTP response waits for all of them. With the flag on, each touch runs eligible, which loads the session's full history (store.context), resolves the model in its Location and estimates the prompt. It then calls FiberMap.run, which interrupts and restarts an already-armed timer. If clients report on a fixed cadence with many tabs open, that cost repeats on every report. Consider touching only sessions whose lease is new (or that have no armed timer), and/or touching them in the background instead of in the request.

@tiomat tiomat changed the title feat(core): idle session compaction before prompt-cache expiry feat: idle session compaction before prompt-cache expiry Nov 15, 2026

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The new client side looks right. The app reports each window's tabs (including the preview tab) per server under a per-window ID in sessionStorage. The TUI reports its tabs plus the session being viewed. Failed or rejected reports are ignored, so older servers are unaffected. idle markers get their own label and stay visible under background compaction. I ran the new reporter tests (7/7 pass). I couldn't run the type check, drive the UI, or produce screenshots, because the marker only appears after a real idle compaction. Could you attach a screenshot or short clip of the new "Session compacted while idle" / "Idle compaction" markers in the app and TUI?

Public API additions since the last review (all additive): createPresenceReporter and createPresence exported from @opencode/client/solid, and the i18n key ui.messagePart.compaction.idle.

The earlier point about the presence handler is not addressed: the server still re-checks eligibility and re-arms the timer for every reported session on every report. With the heartbeat added here, that now happens every minute for every open tab in every window, on servers with the flag on (see the inline comment on the interval). Clients also POST every minute when the flag is off. That is cheap on the server, but it is constant background traffic for a feature that is off in releases.

}
send()
}
const timer = setInterval(refresh, input.interval ?? 60_000)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Leases last 2h on the server, but this refreshes every 60s. Each refresh makes the server run idle.touch for every reported session: with the flag on, that loads the full history, resolves the model and re-arms the timer. Set changes and reconnects already report right away through update, so the heartbeat only needs to keep leases from expiring. An interval well below the lease but far above a minute (e.g. 15–30 min) would cut that server work by an order of magnitude without changing behaviour.

@tiomat

tiomat commented Nov 15, 2026

Copy link
Copy Markdown
Author

Withdrawn: keeping this as a fork-local feature instead of proposing it upstream.

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

Labels

needs:compliance This means the issue will auto-close after 2 hours.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant