Skip to content

feat(rust): preserve ChatGPT encrypted state across Codex-style model switches #6579

Open

Description

@me2seeks

Problem

On rust-preview, ChatGPT subscription sessions need Codex-style encrypted-state continuity when switching models, including switches to incompatible or smaller-window models. This scope is specifically the ChatGPT subscription (maka.codex / Codex Responses adapter), not generic Responses-compatible providers. Cross-account payload acceptance is confirmed by the requesting user; equal trusted hashes may permit reuse across subscription accounts, and account/connection identity is recorded as provenance and used to isolate discovery caches, not as an additional replay prohibition.

At inspected Rust head da2fbf3b9b91114de4cac56988aee04a6d6550b7:

  • Codex inventory decoding does not preserve comp_hash.
  • Reasoning replay admission compares exact model/route identities on continuation paths; ordinary turns must be audited and brought under the same policy.
  • ContextCheckpoint stores a portable TextSummary, not an opaque native Codex compaction state.
  • Request provenance and frozen-request reconstruction must preserve the exact encrypted-state admission decision across restart.

Related #6361 concerns the TypeScript runtime; #6385 documents why connection ID alone cannot establish account continuity. This issue tracks the Rust implementation.

Desired outcome

Implement the ChatGPT subscription usage and switch flow by reference to OpenAI Codex, including native compaction rather than making portable text summarization the primary switch path. Manual /compact on a ChatGPT subscription session must invoke native Codex compaction and persist/replay its opaque result, rather than issuing the current ordinary text-summary request. This is part of this issue, not a later enhancement.

Reference inspected at upstream commit ba0d0e1f74ee0f41c27ef24b37ed5fc030b487e7:

  • Pre-sampling model switch logic: compact when both compaction hashes are present and differ, or when switching down to a smaller window and the active context reaches the target's relevant threshold. A missing hash does not establish a change or prove compatibility.
  • Native compaction installation and fallback: the previous model processes the old window, the replacement context belongs to the target model, and qualifying failures may retry compaction using the target model. Do not infer that arbitrary failed requests or oversized windows can always be retried safely.
  • Compaction fallback policy.

Target flow:

  1. Host prepares fresh subscription model metadata and captures immutable producer provenance for opaque state. Do not add same-account or same-connection replay restrictions; scope directory freshness and provenance to the actual subscription identity.
  2. On a compatible model switch, preserve admitted encrypted reasoning/native compaction state and subsequent messages, rather than expanding covered history solely because the model ID changed.
  3. Before the first ordinary target-model inference, detect compatibility changes and context downshifts using upstream's policy as the reference. Use the previous model/access identity to compact the captured old context; assemble replacement history using the target's instructions, options and context budget. Carry the new user message after the captured history rather than silently folding it into the old-window summary.
  4. Persist and validate the checkpoint/replacement before adopting it. Preserve source coverage, tool call/result pairing, unknown outcomes, head anchors, concurrent suffix events, and the original event log.
  5. Include target instructions, tools, required suffix/new message, images and output reserve in capacity handling. Local sizing is a preflight policy, not proof of provider acceptance; target rejection must have bounded, explicit recovery without repeating tools or destroying the original context.
  6. If the old model is unavailable or compaction fails, apply an explicitly tested upstream-derived fallback where applicable. If no safe fitting replacement can be produced, report/park the switch execution with recoverable source state; never dispatch incompatible opaque items or silently drop required history. The selected target and whether target inference actually started must remain distinguishable.

Proposed PR sequence

  • PR 1 — Subscription compatibility facts and Host lazy refresh. Preserve comp_hash; capture non-secret connection/account/wire provenance and immutable request evidence. Implement Host-owned on-demand inventory refresh with per-connection single-flight, freshness recheck, bounded jittered backoff and lifecycle/cancellation behavior. Reuse PreparedModelFetch, OAuth accept_credential, and conditional completion. Automatic discovery must preserve the user's model selection and re-read canonical configuration after awaits. No global timer or Desktop ownership.
  • PR 2 — Native Codex compaction checkpoint lifecycle, including manual /compact. Route /compact for the ChatGPT subscription provider through native compaction. Add a typed opaque native checkpoint alongside the existing text checkpoint. Implement actual subscription request/stream handling, durable capture/install/roll-forward, semantic indexing, source coverage and frozen reconstruction. Native output must remain opaque and must not be rendered as a plaintext summary. Reuse the endpoint/request control actually used by the upstream subscription implementation.
  • PR 3 — Unified encrypted-state replay admission. Implemented in feat(agent): unify ChatGPT encrypted state replay admission #6654 (Ready for review; CI pending). Apply one provider-scoped compatibility policy to ordinary turns, continuations/resume/handoff, compaction and frozen requests. Keep exact request route identity separate from state compatibility. Preserve original item IDs, encrypted payloads and wire order. Historical requests rebuild from their frozen evidence; new requests use current admitted evidence. Legacy or missing producer evidence must not be retroactively certified from today's model catalog.
  • PR 4 — Codex-style model-switch preflight and capacity recovery. Implement hash-change and smaller-window triggers, previous-model compaction plus target replacement context, safe checkpoint adoption, qualifying target-model compaction fallback, and explicit recoverable failure. Cover both compatible-but-too-large and incompatible-and-too-large switches.

Review fixes in PR1 and PR2

Follow-up review of PR1 exposed whole-override invalidation even for a display-name edit. Accepted messages now reuse their captured overrides, thinking/tool settings and body controls on later steps and restoration; later defaults apply to new admissions. Only actual provider/transport authority and availability remain validity gates. The original frozen-tool-policy test stays a success-path test. Workhub transaction/pagination fixtures and the long-hash inventory assertion are updated. PR2's latest review found no new blocker in that layer; it follows the corrected base.

PR #6580 separates accepted user controls from live inventory observations and prepares one coherent snapshot per logical request; physical retries remain frozen. Discovery recovery and restoration no longer compare live budgets against an accepted resolved basis. The arbitrary 1,024-entry inventory and 128-byte hash limits are removed. The 270/300-second refresh policy, per-discovery 15-second deadline, account-replacement wait and 30–60-second failure backoff are documented; catalog TTL does not expire recorded checkpoint facts.

PR #6584 consolidates the protocol operation, moves trigger encoding to the Responses adapter, introduces typed terminal native output, derives checkpoint producer/model from its producing request, and exercises text/native background concurrency through the same behavioral scenario. The selected model's original event log, frozen request semantics and source-fence adoption remain authoritative. These changes add no compatibility decoder or special services framework.

PR 2 implementation design — native checkpoint lifecycle

Implemented in PR #6584, based on PR #6580 (GitHub stack #6585). PR 2 implements the lifecycle described below; CI and review status are tracked in that PR.

Verified execution boundary. The existing RunInput::refresh_model() calls ModelSource::capture() per logical step. Native Source::observe() reads canonical local configuration; Source::prepare() resolves credentials and request options. PR #6580 separately adds ChatGPT-only lazy remote inventory discovery. PR 2 reuses this preparation boundary for compaction and records the explicit native operation in request evidence. Installed native checkpoints and subsequent main-request reconstruction retain immutable producing evidence. This PR does not expand the existing in-flight Summary restart/retry lifecycle.

ChatGPT command policy. ChatGPT subscription /compact has exactly one behavior: native Codex compaction, enabled by default. Do not add a text/native mode toggle, ordinary text-summary request, or automatic text-summary fallback for this provider. A native-compaction failure is reported as failure while retaining recoverable history. Other providers retain their own existing text-compaction behavior. Encrypted reasoning replay already exists; native compaction is a different opaque item, and covered historical reasoning must not be redundantly expanded alongside its checkpoint.

Protocol. Follow the inspected Codex V2 implementation at ba0d0e1f74ee0f41c27ef24b37ed5fc030b487e7: append a compaction_trigger input control, use the normal authenticated Responses streaming transport, require response.completed and exactly one compaction output item. The trigger is a request control, not durable history. Do not substitute a text-summary prompt or assume /responses/compact is the subscription protocol. Preserve output identity, encrypted bytes and opaque fields; do not copy upstream's legacy item aliases into this implementation.

References: attempt construction, stream collection and replacement items.

Prompt settings and client contract (revised by requester). Keep the session prompt editor, global text-summary preference, one-off prompt API field and existing Host prompt-query contract unchanged. Keep accepting and saving custom prompts; they remain available when a non-ChatGPT model is selected. ChatGPT subscription compaction always uses native control and does not apply these text-summary prompts to its request or base instructions. Do not hide editors, reject prompt-bearing API calls, or add a mode-selection UI. Verify a supplied custom prompt is not sent as a native summary instruction and remains usable by ordinary text compaction. Audit automatic compaction callers as well as /compact.

Empirical validation. A synthetic-content probe against the current ChatGPT subscription using gpt-6-luna completed native compaction, ordinary replay remembering the marker, and a second native compaction. Checkpoint-only replay plus a new question also retained the marker. The real stream provided one completed compaction item, a response ID and output usage; the item in output_item.done matched response.completed.output. HTTP and WebSocket request parity is additionally covered locally; the live probe used HTTP. Native sizing uses provider output tokens or the captured context-window upper bound; it refuses installation if neither exists. Ciphertext byte size is never treated as input token usage. Hash-transition/server conversion and smaller-window preflight remain PR 3/4 scope.

Request and output types. Extend the existing request-purpose/control vocabulary with an explicit Codex native-compaction operation, carried through Fact::ModelRequested, request composition, frozen reconstruction and both HTTP/WebSocket encoders. It must never be inferred from prompt text. Use one ModelOperation frozen in request evidence. The selected Responses adapter encodes the trigger and returns validated typed NativeCompaction at stream completion; Engine and EventLog do not extract this result from provider-options JSON. Native replay items remain typed prompt-source parts, distinct from TextKind::Thinking and ordinary text. The trigger itself is not an assistant/history part. Transport decoding retains the item without making it user-visible or executing any tool calls emitted during the compaction attempt.

Checkpoint representation. Replace the text-only checkpoint payload with a tagged content enum: portable text and Codex native replacement. Preserve the common coverage fence, source digest, predecessor and producing-step identity. The native variant stores the item digest and conservative token estimate; the existing producing-step reference resolves the original typed completed-event item. Producer/model facts are derived from that producing request in the baseline projection, not stored again in the checkpoint. The payload is stored once in the producing completion and borrowed through its shared JSON owner when reading a baseline, rather than copied into checkpoint/index headers. The existing closed source fence and required suffix determine replacement history; PR 2 does not add optional retained-user/image policies from upstream. Update readers, validation, semantic indexes and history projections together; add no old-format decoder, migration shim or aliases. The portable text variant remains the ordinary non-subscription feature, not a fallback after failed ChatGPT native compaction.

Capture and installation. Route ChatGPT subscription /compact through the native job in engine/src/compact.rs; select by the admitted provider identity, not merely by the Responses protocol. Capture the closed source and predecessor first, send the native request, journal its completed output, validate that the output and producer request prove the exact source fence, and durably install the checkpoint before reporting success. Reuse existing source coverage, required suffix, tool pairing and source-fence rules. Covered closed history is represented by the native checkpoint; events outside that closed fence retain their existing projection and order. Events after the captured fence remain suffix events and are never lost or folded into the wrong checkpoint.

Replay and roll-forward. The next same-model request composes native replacement items plus suffix; a second /compact consumes that checkpoint plus new closed history and installs its successor. Restarted ordinary execution resolves the same checkpoint item; frozen request evidence carries the explicit operation and native prompt identity. Existing in-flight compaction recovery policy is unchanged. Provider usage and opaque-state size uncertainty must remain explicit; ciphertext byte length is not a plaintext token count. UI/history renders a compaction status, never the opaque payload as a text summary.

Failures. Cancellation, malformed/missing/duplicate native output, interrupted completion and failed checkpoint persistence leave the old baseline and source recoverable. An observed item without a completed response is not installable. Retry only through the existing bounded replay-safe attempt lifecycle, without re-running tools. Native failure does not silently issue a text summary. Missing fresh hash is recorded as missing producer evidence, never stamped from an old catalog.

Boundaries and acceptance. PR 2 delivers manual native /compact, same-model reuse and roll-forward, checkpoint replay after restart, and native operation/identity in frozen evidence. Cross-model hash-based admission remains PR 3; old-model-to-target preflight and smaller-window recovery remain PR 4. Local coverage includes both transport encoders, stream completion/incompletion, persistence proof forgery rejection, /compact -> ordinary turn -> /compact, restart, continuation after a native prefix, same-model hash-change re-compaction without new messages, cancellation before stream completion, and rejection before dispatch when native capability lacks subscription producer facts. The existing text background-concurrency/retry scenario now also runs with native compaction: Main overlaps the compactor, capture coverage stays fixed, the suffix is retained exactly once, and a physical retry retains its original frozen request. Existing text-history, auto-context, handoff, pruning, frozen-request and store regressions also pass. Engine tests exercise real event-log capture and installation.

Acceptance tests

  • Manual /compact on a ChatGPT subscription session emits the native compaction request control/endpoint used by Codex, records an opaque native checkpoint (not TextSummary), and the next ordinary request reuses that checkpoint plus the preserved suffix. A second manual /compact rolls forward the native checkpoint. Cover cancellation, provider rejection, restart, and checkpoint persistence failure; do not silently report text summarization as successful native compaction.

  • Real subscription probe for ordinary encrypted reasoning (not only visible summary text) across a compatible model pair; native compaction replay and roll-forward tested separately.

  • Two subscription accounts/connections with equal trusted hashes can reuse opaque state; re-login/account replacement and normal token refresh do not contaminate discovery cache identity.

  • Hash mismatch, missing metadata, stale/future timestamps and provider errors never authorize an unsupported cross-model replay; fresh metadata is not inferred for old state.

  • Compatible switch below the target threshold avoids unnecessary compaction. Compatible downshift above the threshold and incompatible switch both follow pre-sampling compaction policy.

  • Large-window A -> incompatible small-window B: previous-model compaction occurs before B's first ordinary inference; B receives the replacement plus the new message. Test insufficient target budget, large new messages/images/tools and provider context-overflow rejection.

  • Failed/cancelled/unknown compaction installation leaves the original history recoverable; tool effects are not repeated; changes during capture do not lose the suffix.

  • Warm execution, Host restart, manual compaction, resume/handoff and frozen request reconstruction all preserve the same admission semantics.

  • Concurrent turns share one discovery request; a cancelled waiter does not cancel other waiters; configuration or credential replacement supersedes old discovery; normal OAuth refresh uses the accepted credential path; backoff resets appropriately after identity changes/manual refresh.

Alternatives or workarounds

Rust's current text checkpoint is a portable fallback, but it does not provide native encrypted-state continuity. The primary requested implementation follows Codex's subscription behavior. Generic provider portability, global periodic catalog refresh are outside this issue.

Activity

  1. added
    enhancement
    on Nov 2, 2026
  2. self-assigned this
    on Nov 2, 2026
  3. M4n5ter commented on Nov 3, 2026

    @M4n5ter
    Member
    English

    I support this feature and using openai/codex as a reference. Native compaction, model switching and encrypted-state continuity are worth implementing, and persistence, history-coverage proofs and task settlement deserve careful handling.

    After reading the model preparation, compaction, history projection and storage paths, I think the implementation needs consolidation. We already have duplicated facts, provider protocol details spreading across layers, and live catalog observations mixed with accepted configuration. I would like us to address those in the first two layers before building the next two on top.

    First, a few upstream facts:

    • comp_hash identifies compaction-compatible model configurations. Upstream triggers this pre-sampling compaction when both hashes are present and differ; a missing hash is not automatically known incompatibility. Upstream explanation
    • Upstream does use a 300-second model-catalog cache TTL. This is a refresh policy, not an expiration time for historical checkpoints or provenance. Cache definition
    • Authentication-generation checks on background candidates do not, by themselves, establish a same-account-only restriction for replaying historical state.

    With those distinctions in place, I would like the following addressed.

    1. Separate accepted configuration, live model observations and the snapshot for one logical request.

    ExecutionBasis retains resolved capabilities, options and output budget, then compares that whole structure with a resolution based on the refreshed catalog. When derived values such as the output budget change, an accepted execution can be rejected even though the user changed nothing. Meanwhile, request context continues to come from the old accepted context. The boundary between what updates and what stays frozen is inconsistent.

    Please make explicit which accepted user choices must remain fixed and which provider facts may update, then freeze the actual parameters for each logical request. Physical retries must continue using the original request snapshot. Fixing this fact model should take priority; restoring the old capacity fallback would not address the root cause.

    2. Bring Codex protocol details back to their boundary.

    Native compaction is currently expressed through ModelOperation, ProviderOperation, CodexCompactionTrigger in assistant content, and the recipe, overlay, serialization and measurement paths. Its result first goes into provider_options.openai.compaction, which the engine and storage layers then interpret as provider JSON.

    Maintainers have to follow several representations of the same operation, and other protocol encoders also acquire new branches. That cost will grow with the subsequent features.

    Please work through the existing boundaries: Provider declares capabilities, Host prepares and freezes facts, the adapter encodes operations and interprets native results, and the engine owns the common lifecycle. Keep the business-purpose distinction between Main and Summary, consolidate the repeated protocol-operation representations, and keep the trigger at the adapter boundary.

    3. Remove duplicated producer facts from checkpoints.

    A checkpoint already refers to its producing request through summary_step_id, and validation already reads that request. It nevertheless stores another producer/model copy and proves that the two copies agree.

    Keep the step reference, content digest and history-coverage proof, and derive producer/model from the original request when reading. This removes persistent state that otherwise needs synchronization, along with its consistency rules.

    4. Remove limits without a demonstrated basis, and distinguish cache policy from functional restrictions.

    I have not found an actual basis for the 1,024-entry cache limit or 128-byte hash limit. Reaching the cache capacity also stops discovery for new connections, affecting ordinary functionality. Please remove limits that have no real constraint behind them.

    The 300-second value has an upstream cache-policy precedent; that fact should be retained. The 270-second early refresh, 15-second timeout and 30–60-second backoff should each have their rationale explained. Numbers should not all be retained or removed merely because they are numbers.

    5. Explain the foreground waiting policy for catalog refresh.

    The existing async compaction starts background execution after capture completes. Upstream also performs necessary foreground preparation, so that structure is not itself a problem.

    The added catalog refresh can, however, await network I/O inside capture. Please explain which operations require a new observation, which ordinary requests may proceed without one, and the latency tradeoff for a cold cache or slow network. Background-task ownership and how long the foreground waits are separate concerns that both need an answer.

    This point concerns waiting policy and latency tradeoffs. I am not classifying it as a demonstrated async-compaction regression.

    6. Add one direct behavioral check for native background concurrency.

    The existing text-compaction tests cover foreground progress, a frozen history cutoff, preservation of new messages and tool suffixes, and physical retries of a frozen request. Those are valuable and should remain.

    The native-compaction tests cover persistence, failure, cancellation and recovery, but do not yet establish the same background-concurrency behavior. Please reuse the existing scenario to show that native compaction really overlaps Main, that adoption preserves the suffix exactly once, and that the original request's retry semantics remain intact.

    Keep validation focused on these real behaviors rather than expanding it into many repetitive assertions about private state and call order.

    I would address the first four points before merging, explain the tradeoff in the fifth, and close the coverage gap in the sixth. The exact interfaces are open for discussion, but the outcome should reduce duplicated state and cross-layer special cases while completing the feature through the existing execution, logging and async-compaction mechanisms.

    简体中文

    我认可这项能力,也认可参考 openai/codex 的实现。原生压缩、模型切换和加密状态延续值得做,相关的持久化、历史覆盖证明和任务结算也确实需要认真处理。

    但看过这组改动的模型准备、压缩、历史投影和存储路径后,我认为当前实现还需要收敛。现在已经出现了同一事实重复保存、提供商协议细节扩散,以及动态目录观测与已受理配置混用的问题。希望先在前两层处理这些问题,再继续推进后两层。

    先把上游依据说清楚:

    • comp_hash 是压缩兼容配置组的标识。上游只在前后 hash 都存在且不同时,触发这项前置压缩;缺失不能直接当作已知不兼容。上游说明
    • 上游确实使用 300 秒模型列表缓存 TTL。这是刷新策略,不是历史检查点或来源事实的有效期。缓存定义
    • 后台候选的认证 generation 检查,也不能直接推广为历史状态必须同账号才能复用的限制。

    基于这些前提,我希望处理以下事项。

    1. 修正已受理配置、动态模型观测和单次请求快照的边界。

    ExecutionBasis 保存了解析后的能力、选项和输出预算,之后又拿刷新模型列表后的解析结果整体判等。当刷新前后输出预算等派生值发生变化时,用户没有修改过的已受理执行也可能被拒绝。与此同时,请求 context 又继续沿用旧的 accepted context,更新与冻结的边界并不一致。

    请明确哪些用户选择必须保持不变,哪些提供商事实允许更新,再为每个逻辑请求冻结实际参数。物理重试继续使用原请求快照。这里应优先修正事实模型,恢复旧容量兜底并不能解决根因。

    2. 收回散落在通用层的 Codex 协议细节。

    目前原生压缩要通过 ModelOperation、ProviderOperation、助手消息中的 CodexCompactionTrigger,以及 recipe、overlay、序列化和计量路径共同表达。结果又先进入 provider_options.openai.compaction,再由执行层和存储层解析供应商 JSON。

    维护者需要跨多个地方核对同一件事,其他协议编码器也要跟着增加分支。这个成本会随着后续能力继续扩大。

    建议沿用现有边界:Provider 声明能力,Host 准备并冻结事实,适配器编码操作、解释原生结果,执行引擎负责通用生命周期。保留 Main/Summary 的业务用途区别,收敛重复的协议操作表达,让触发命令留在适配器边界。

    3. 删除检查点中重复保存的来源事实。

    检查点已经通过 summary_step_id 引用来源请求,验证时也会读取原请求,却又保存一份 producer/model,再证明两份数据相等。

    建议保留步骤引用、内容摘要和历史覆盖证明,读取时从原请求派生 producer/model。可以少维护一份持久状态,也少一套一致性约束。

    4. 清理没有依据的限制,并区分缓存策略与功能限制。

    目前没有看到 1024 条缓存上限、hash 128 字节上限的实际依据。缓存达到容量后直接停止新连接刷新,还会影响正常功能。没有真实约束依据的上限,请删除。

    300 秒有上游缓存策略作为参考,应当保留这个事实。270 秒提前刷新、15 秒超时和 30–60 秒退避则分别说明取值依据即可,不应因为它们都是数字就一概保留或删除。

    5. 说明模型列表刷新的前台等待策略。

    现有异步压缩是在 capture 完成后启动后台执行;上游也有必要的前台准备,这个结构本身没有问题。

    但新增的模型列表刷新可能在 capture 中等待网络。请说明哪些操作必须等到新观测,哪些普通请求可以继续,以及冷缓存、慢网络时的延迟取舍。后台任务的所有权和用户前台需要等待多久,是两个需要分别交代的问题。

    这一项目前属于等待策略和性能取舍,我没有把它认定为已经证实的异步回归。

    6. 补一条直接验证原生后台并发的行为测试。

    现有文本异步压缩测试覆盖了主流程继续推进、固定历史截止点、保留新增消息及工具后缀,以及冻结请求的物理重试。这些覆盖有价值,应当保留。

    目前原生压缩测试覆盖了持久化、失败、取消和恢复,但还不足以证明它保持了同样的后台并发语义。建议复用现有场景,验证原生压缩与 Main 真正重叠,采用结果后后缀恰好保留一次,并保持原请求重试语义。

    验证应集中在这些实际行为上,避免再围绕私有状态和调用顺序展开大量重复测试。

    前四项我建议在合并前处理;第五项请明确取舍,第六项补齐关键验证。具体接口可以继续讨论,但希望最终能减少重复状态和跨层特例,沿现有执行、日志和异步压缩机制把能力接完整。

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

Metadata

Metadata

Assignees

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions