Repository navigation
feat(agent): unify ChatGPT encrypted state replay admission - #6654
Conversation
Use producing request provenance to admit compatible cross-model and cross-account reasoning and native checkpoints. Keep frozen request observations independent of current metadata and preserve route authority. Refs #6579 Generated-by: Codex
M4n5ter
left a comment
There was a problem hiding this comment.
English
Reviewed 4ddb4484a. Moving encrypted-state replay admission out of the wire adapter and distinguishing ModelOperation::Inference from ModelOperation::CodexCompaction goes in the right direction, as does preserving the original request snapshot across physical retries.
Before this can land, there are four issues across sealed handoff execution, storage/layering boundaries, cross-provider reasoning projection, and the new tests that need to be addressed:
1. ChatGPT handoff resumption breaks across host restart and catalog refresh (plugins/agent/native/src/owner/execution.rs:432-485, plugins/agent/engine/src/lib.rs:681, plugins/agent/engine/src/continuation.rs:145-159, 198-210, plugins/agent/native/src/owner/goal/dispatch.rs:179-212, plugins/agent/engine/src/steps.rs:238, 263-344)
- When a run seals a
HandoffPause(steps.rs:311-323),pause.execution.contextfreezesCodexRequestProvenanceincludingCodexCompatibility { comp_hash, fetched_at }. CodexInventory(plugins/agent/native/src/model/codex_inventory.rs:39-40) is in-memory only, refreshes afterREFRESH_AT = 270s, and expires atMAX_AGE = 300s. Across any host restart (the primary handoff boundary) or after 4.5 minutes in-process,resume_goal_handoffcallsprepare_frozen_retry->source.capture(), producingsettings.contextwith a newfetched_at(orcompatibility: None/ a rotatedcomp_hash) and passingcontext: settings.contextintoRunWork::Handoff.- Even when
comp_hashis unchanged,CodexCompatibilityderivesPartialEqoverfetched_at(plugins/agent/facts/src/context.rs:133-139), soEngine::start_model(engine/src/lib.rs:681:input.context != pause.execution.context) fails withRunError::InvalidInput("handoff execution settings changed"). - If
comp_hashrotated orcompatibilityexpired toNone,continuation::inspect(continuation.rs:145-210) projects history under the newinput.context, drops prior reasoning items, and failsreplay != pause.execution.replaywithRunError::InvalidInput("handoff admission replay changed after sealing"). - In both cases,
goal/dispatch.rs:187-211treatsRunError::InvalidInput(_)as a user settings change, cancels the handoff, and callssaved.goal.pause_for_settings(), stopping the active/goalloop even though the user changed nothing.
- Even when
- Relatedly,
steps.rs:238mutates*input = frozen_input;when rehydrating a retry. If that retried step finishes and the next loop iteration entershandoff.boundary(steps.rs:263-323) beforeinput.refresh_model(steps.rs:344),HandoffPauseseals the stale retry snapshot instead of the live model state. - Please align sealed handoff admission with the sealed execution contract (admit against the sealed snapshot while keeping live
model_sourcerefresh for subsequent steps, and avoid leaking retry-onlyfrozen_inputoverrides into the next step's handoff boundary), and add a handoff test wherefetched_atandcomp_hashadvance across reopen.
2. Keep SemanticSelection free of engine-only pass-through state, avoid duplicating full CodexRequestProvenance onto every AssistantPart, and do not rewrite frozen directory bytes without migrating storage (platform/event-log/src/context/semantic.rs:56-65, plugins/agent/facts/src/history/semantic.rs:80-87, plugins/agent/facts/src/history/semantic/directory.rs:22-24, 76-81, platform/event-log/src/context/semantic/directory/scan.rs:502-567, platform/event-log/src/context/semantic/directory/codec/tests.rs:287-308)
- Pass-through state in
platform/event-log:SemanticSelection.model: Option<SemanticModel>is never read anywhere inplatform/event-log;maka-agent-engine(model_attempt.rs:203) writes it intoselectiononly to read it back fromcaptured.selection().modelinprepared.rs:279, 547andbacked.rs:108. Pass target model / replay parameters directly insidemaka-agent-engine(history::prepared::capture/ProjectContext) instead of extendingmaka_event_log::context::semantic::SemanticSelection. - Per-part provenance duplication on the write/scan hot path: Replay admission only inspects
TextKind::Thinkingparts and only depends on whether the producer was Codex plus its optionalcomp_hash(connection_id,account_id, andfetched_atare never consulted). Cloning the entireOption<CodexRequestProvenance>onto everySemanticKind::AssistantPart(withoutskip_serializing_if = "Option::is_none", emitting"codex":nullintorow_jsonfor every text/tool-call/tool-result part across all providers) and SHA-256 hashing it into everyRowDirectory::AssistantPartduplicates unused provenance on every part. Either derive producer replay basis from the step'sModelRequestedfact or record only minimal Codex replay basis where needed. - Broken persisted
RowDirectorylayout & edited guard fixture:directory.rs:22-24andcodec/tests.rs:287-288explicitly document thatRowDirectoryPostcard bytes are persisted incontext_semantic_rows.directory_bytesand require a migration/rebuild if changed. InsertingcodexintoRowDirectory::AssistantPartin place without rebuildingdirectory_bytes—and updating the hex fixture infrozen_rowdirectory_bytes_keep_their_meaning(codec/tests.rs:304-307)—causes existing SQLite sessions containingassistant_partrows (source_sequence >= 2) to failcodec::decodewith"invalid directory descriptor". Any persisted descriptor change must come with a clean storage rebuild/migration (like0017_steering_observations.sql), never by editing the frozen byte guard test alone.
3. Preserve visible plaintext reasoning summaries when switching from ChatGPT to plaintext-reasoning targets (plugins/agent/engine/src/history/source_projector.rs:192-201, 384-389, 510-517)
- ChatGPT
reasoningitems decode both visiblesummary_textintotextand encrypted state intoprovider_options(plugins/agent/provider-protocol/src/responses/decode.rs:524-552). - When switching from standard OpenAI Responses (
codex: None) toProviderKind::OpenResponses(PlaintextContent)(source_projector.rs:510-517) orProviderKind::OpenaiChatCompletions(plugins/agent/model/src/adapters/wire/chat_source.rs:428-433), OpenAI encryptedprovider_optionsare stripped/ignored while the visible plaintexttextis replayed. - Returning
ProjectedRow::Skipatsource_projector.rs:192-201beforeproject_textwhenevercodex.is_some() && target.codex.is_none()drops the visible plaintext reasoning summary even for targets that never replayreasoningEncryptedContent. Only encrypted OpenAI replay (ProviderKind::OpenaiResponses/provider_options) needs to be gated; plaintext-capable targets should strip incompatibleprovider_optionsrather than dropping non-emptytext.
4. Fix deterministic test timeouts and keep tests focused on observable wire behavior (plugins/agent/engine/tests/integration/codex_replay.rs:35-94, 97-172, plugins/agent/engine/src/frozen_request/tests.rs:232-520)
codex_replay::reasoning_replay_uses_producing_evidence_across_models_accounts_and_restartruns an 8-iteration loop that performs 16 serial coldSessionFixture::open(all SQLite migrations + WAL fsyncs) andCodeExecutorstartups inside a hardcoded90stokio::time::timeout. Running this single test solo locally exceeds 90s (90.06s) and panics withElapsed(()); running the 4codex_replaytests together also pushescompatible_native_switch_replays_and_recompacts_across_accounts_after_restartpast its45stimeout. Reuse oneRootFixture/Engineacross distinct session IDs for the compatibility matrix, reserving physical reopen for a single dedicated persistence check.codex_replay.rs:35-38hardcodesfetched_at: 1everywhere, masking the catalog-refresh handoff bug above.- In
frozen_request/tests.rs:232-520, avoid hand-assembling rawModelRequested/ModelCompletedfacts in afor seed in [true, false]loop and walking internalPreparedPromptrecipe trees (assert_opaque_reasoning); assert retry behavior through the actual execution/wire request output instead.
简体中文
看完了 4ddb4484a。把加密状态回放准入从 wire adapter 上移到投影边界、区分 ModelOperation::Inference 与 ModelOperation::CodexCompaction,以及在物理重试时保留原请求快照,整体方向是对的。
在合并前,有 4 个涉及密封 Handoff 恢复、存储与分层边界、跨协议推理投影以及测试质量的实际问题需要处理:
1. ChatGPT 订阅下的 Handoff 恢复在进程重启或目录刷新后会必现失败并误停 Goal(plugins/agent/native/src/owner/execution.rs:432-485、plugins/agent/engine/src/lib.rs:681、plugins/agent/engine/src/continuation.rs:145-159, 198-210、plugins/agent/native/src/owner/goal/dispatch.rs:179-212、plugins/agent/engine/src/steps.rs:238, 263-344)
- Turn 在
steps.rs:311-323封存HandoffPause时,pause.execution.context会冻结当时的CodexRequestProvenance(含CodexCompatibility { comp_hash, fetched_at })。 CodexInventory(plugins/agent/native/src/model/codex_inventory.rs:39-40)是纯内存缓存,REFRESH_AT = 270s、MAX_AGE = 300s。只要经过进程重启(Handoff 的核心场景,内存缓存必为空)或同进程内超过 4.5 分钟,resume_goal_handoff调用prepare_frozen_retry->source.capture()就会生成带新fetched_at(或compatibility: None/ 新comp_hash)的settings.context并传入RunWork::Handoff:- 即使
comp_hash完全未变,CodexCompatibility(plugins/agent/facts/src/context.rs:133-139)直接#[derive(PartialEq)]比较fetched_at,导致Engine::start_model(engine/src/lib.rs:681:input.context != pause.execution.context)直接报RunError::InvalidInput("handoff execution settings changed"); - 若期间
comp_hash轮换或目录短暂过期为None,continuation::inspect(continuation.rs:145-210)按新input.context投影历史并丢弃旧推理分片,触发replay != pause.execution.replay,报RunError::InvalidInput("handoff admission replay changed after sealing"); - 两种情况都会被
goal/dispatch.rs:187-211当作用户修改了会话设置,直接cancel_handoff并调用saved.goal.pause_for_settings()暂停整个/goal自动循环。
- 即使
- 同时,
steps.rs:238在重试恢复时直接执行*input = frozen_input;;若重试步完成后下一轮循环在steps.rs:344(input.refresh_model)之前进入handoff.boundary(steps.rs:263-323),会把过期的重试快照封进新的HandoffPause。 - 请对齐 Handoff 密封执行的准入契约(准入阶段基于密封快照校验,同时保留实时
model_source供后续步骤刷新,且不要让重试步的frozen_input污染下一步的 handoff 封存),并补充重启后fetched_at与comp_hash变化的 Handoff 回归测试。
2. 不要向 platform/event-log 塞入透传字段、避免在每个 AssistantPart 上冗余复制整份 CodexRequestProvenance,且不得靠修改冻结字节测试绕过存储迁移(platform/event-log/src/context/semantic.rs:56-65、plugins/agent/facts/src/history/semantic.rs:80-87、plugins/agent/facts/src/history/semantic/directory.rs:22-24, 76-81、platform/event-log/src/context/semantic/directory/scan.rs:502-567、platform/event-log/src/context/semantic/directory/codec/tests.rs:287-308)
platform/event-log中的纯透传字段:SemanticSelection.model: Option<SemanticModel>在整个platform/event-log中没有任何读取点,只是被maka-agent-engine(model_attempt.rs:203)塞进selection后又在prepared.rs:279, 547和backed.rs:108从captured.selection().model取回。请直接在maka-agent-engine(history::prepared::capture/ProjectContext)内部传参,不要污染maka_event_log::context::semantic::SemanticSelection。- 热路径每分片写放大与冗余来源事实:回放准入只检查
TextKind::Thinking分片,且只依赖来源是否为 Codex 及可选comp_hash(从不读取connection_id、account_id、fetched_at)。当前实现把整份Option<CodexRequestProvenance>复制到了每一个SemanticKind::AssistantPart(甚至未加skip_serializing_if = "Option::is_none",导致所有渠道的普通文本、ToolCall、ToolResult 分片都在row_json写出"codex":null),并在scan.rs:514, 561对每个分片做 SHA-256 目录度量。应从对应步骤的ModelRequested派生,或仅在需要处记录最小回放依据。 - 原地破坏持久化
RowDirectory二进制布局并修改守卫测试:directory.rs:22-24与codec/tests.rs:287-288明确约束RowDirectory的 Postcard 编码持久化在context_semantic_rows.directory_bytes中,变更字段顺序必须配套迁移或重建。当前直接在RowDirectory::AssistantPart中插入codex而未迁移存储,并同步修改了frozen_rowdirectory_bytes_keep_their_meaning(codec/tests.rs:304-307)里的十六进制冻结字节,会导致包含任意历史assistant_part(source_sequence >= 2)的本地 SQLite 会话在读取时直接报"invalid directory descriptor"。若确实需要调整持久化描述符,必须像0017_steering_observations.sql一样同步重建/迁移,不能通过改掉守卫 fixture 掩盖。
3. 从 ChatGPT 切换到明文推理渠道时不应丢弃可见推理摘要(plugins/agent/engine/src/history/source_projector.rs:192-201, 384-389, 510-517)
- ChatGPT 的
reasoning同时解码了可见明文summary_text(存入text)与加密provider_options(plugins/agent/provider-protocol/src/responses/decode.rs:524-552)。 - 普通 OpenAI Responses(
codex: None)切往ProviderKind::OpenResponses(PlaintextContent)(source_projector.rs:510-517)或ProviderKind::OpenaiChatCompletions(plugins/agent/model/src/adapters/wire/chat_source.rs:428-433)时,都会剥离或忽略加密provider_options并保留可见明文text。 - 当前在
source_projector.rs:192-201只要codex.is_some() && target.codex.is_none()就在进入project_text前直接ProjectedRow::Skip,导致切往根本不发送reasoningEncryptedContent的明文推理渠道时也丢失了可见推理摘要。应仅对需要重放加密载荷的目标拦截,对支持明文推理回放的目标剥离不兼容的provider_options即可。
4. 修复必现超时的集成测试,并围绕可观测的 wire 行为编写测试(plugins/agent/engine/tests/integration/codex_replay.rs:35-94, 97-172、plugins/agent/engine/src/frozen_request/tests.rs:232-520)
codex_replay::reasoning_replay_uses_producing_evidence_across_models_accounts_and_restart在单个测试的 8 次循环中串行执行了 16 次完整的SessionFixture::open(全量 SQLite 迁移 + WAL fsync)与CodeExecutor冷启动,并硬编码90stokio::time::timeout。本地单独运行该测试即耗时90.06s必现Elapsed(())panic;并行运行codex_replay时还会连带拖垮compatible_native_switch_replays_and_recompacts_across_accounts_after_restart(45s超时)。矩阵用例请复用同一个RootFixture/Engine下不同 session ID 验证,仅保留一次独立的物理重开验证持久化即可。codex_replay.rs:35-38将fetched_at全部硬编码为1,掩盖了上面的目录刷新与 Handoff 问题。frozen_request/tests.rs:232-520用for seed in [true, false]手工拼装底层ModelRequested/ModelCompleted事件并递归遍历内部PreparedPromptrecipe 树(assert_opaque_reasoning),耦合内部实现细节;建议直接通过真实重试执行路径断言最终发出的 wire 请求。
Admit handoffs with sealed execution facts and keep retry snapshots local to their step. Read original request context by invocation and step without changing persisted directory bytes or duplicating provenance. Preserve plaintext summaries and verify actual wire replay with shared test resources. Refs #6579 Generated-by: Codex
Astro-Han
left a comment
There was a problem hiding this comment.
I reviewed all 21 changed files at fadc5ea and the earlier review 5795871008. There is a new integration P2 against current rust-preview 9c67d19.
P2: migrate the new original-request lookup to the current SQLite API before merging. platform/event-log/src/context/semantic/captured.rs:361–374 still returns Box::pin(async move { ... sqlx::query_scalar(...).await ... }) from connection.read. The automatic merge into 9c67d19 has no textual conflict, but #6671 removed EventLog's sqlx dependency and changed read to require a synchronous FnOnce(&mut rusqlite::Connection) -> Result<T, StoreError>. I extracted this exact method from the actual merged tree and the exact current read signature into a controlled type adapter. The adapter compiles without the method; enabling the unchanged method produces E0433 (unlinked sqlx) and E0308 (a pinned future where Result is required). This is an isolated interface compilation, not a full workspace build. Port the lookup to the current connection and storage representation, then check the merged EventLog and Engine.
The revision substantially addresses the previous review's four areas. Sealed handoff input uses its recorded execution fields while preserving the live model source; frozen retry overrides remain local to the step, including retry and approval parking. Replay target policy is passed directly through Engine. I compared the persisted RowDirectory, frozen-byte guard and SemanticSelection blobs with the base: all three are unchanged. The producing-request SQL selects by the semantic row's invocation and step identity; controlled SQL rows confirm it ignores a completion-order distractor and another invocation. Twelve cases against the actual replay predicate cover same/different model, matching/missing/mismatching hashes and inference/re-compaction. Plaintext-capable targets strip incompatible encrypted metadata while preserving visible reasoning.
I also inspected the actual hosted results, rather than treating the author's local summary as my run. In CI 42251999589, rest-2 jobs 128027220510 and 128027221130 pass 236 and 235 Engine tests respectively, including all five codex_replay tests and the refreshed-hash handoff scenario. Both jobs checked out 3d8672a, merging this head into 500d53b, before the storage rewrite; those passes do not validate the new 9c67d19 merge. The eight-case matrix now shares one Root/Engine, retains a separate physical reopen case, and checks actual 429 retry request equality. I did not locally run the complete workspace, real OAuth subscription replay or a native Host restart. The earlier live-service result remains author-provided evidence. No approval or merge performed.
Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.
| .connection | ||
| .read(move |db| { | ||
| Box::pin(async move { | ||
| Ok(sqlx::query_scalar( |
There was a problem hiding this comment.
P2 — port this lookup to the current synchronous SQLite connection.
A merge into current rust-preview 9c67d19 is textually clean but leaves this SQLx call and its Box::pin(async ...) closure intact. EventLog no longer depends on SQLx, and its read now expects FnOnce(&mut rusqlite::Connection) -> Result<T, StoreError>. Compiling this exact method with the actual current signature in a controlled adapter confirms E0433 and E0308. Adapt the query to the current storage API and check the merged result; CI tested merge 3d8672a against the older 500d53b base.
Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.
Astro-Han
left a comment
There was a problem hiding this comment.
I rechecked e93873f991f8e634101e07373e498cabb487fa20 against current rust-preview 714d8c47. The previous integration P2 is fixed: request_context now executes its producing-request lookup synchronously through rusqlite::Connection::query_row, matching the current SQLite reader API.
I compared the two original author commits with their earlier versions using range-diff; both are unchanged. I also made actual automatic merges of the old and new heads into the same current Rust base. Both merges succeed, and their entire resulting-tree difference is the SQLx-to-rusqlite adaptation of this lookup. This separates the repair from upstream's storage rewrite. An isolated Rust harness compiles the exact new method and current reader signature using rusqlite 0.41.0. Controlled SQLite rows select the original producing request despite another invocation, a completion-order distractor and a later request; a missing request is not invented. The context/domain/reader execution types are adapters, so this is not a full Engine or Host restart run.
I found no confirmed additional P0–P2 in this integration change. CI 42384892389 is terminal failure: its logs show a default-sandbox settings mismatch (workspace-write versus danger-full-access) and the existing missing parent/child approval control. The same settings assertion also fails in the independent test-only PR #6694, while the parent/child test is corrected there. These observations do not establish the cause of the remaining settings failure here. I did not locally repeat real OAuth replay, the full workspace suite or a native Host restart; earlier pre-merge author results remain author evidence.
Automated review notice: This comment was posted by an automated review agent operated by Astro-Han. It is not an independent human review and does not replace one.
Summary
ChatGPT subscription requests replay encrypted reasoning and native checkpoints across models, accounts and connections when the producing and consuming requests record matching
comp_hashvalues. Same-model requests tolerate missing hashes; a known mismatch prevents ordinary encrypted replay. Explicit native re-compaction may send old state to its producing model. Incompatible native checkpoints stop execution before target inference and remain recoverable; switch conversion and smaller-window preflight remain PR4.Replay policy stays in Engine and is passed directly into history preparation. EventLog reads the original ModelRequested context using the captured row's invocation and step identity: ordering positions can refer to completion events, so they are not request identities. No full provenance is duplicated onto assistant parts, no target execution policy is stored in SemanticSelection, and the persisted directory layout and original frozen-byte guard remain unchanged.
Sealed handoff admission uses the recorded execution snapshot while retaining current credentials, route checks and a live model source for subsequent steps. Physical retries use a step-local frozen snapshot, including retry/approval parking, without overwriting the next step's live input. Plaintext-capable targets keep visible reasoning summaries with incompatible encrypted metadata removed; existing non-Codex continuation rules remain in place.
Refs #6579. Layer 3/4, following merged #6580/#6584. This PR targets
rust-previewand is registered with gh-stack for PR4. The completed stack #6585 cannot be extended because its preceding head branch was deleted. No compatibility decoder, migration shim, timer or additional service is introduced.Verification
Upstream
0a5ce771a9is merged. The producer-context query now uses the upstream synchronous SQLite reader. Engine and test-target offline compilation pass after the merge; Native validation could not complete becauseagent-client-protocol 5.0.0is not cached and network dependency retrieval was unavailable. Hosted CI must validate this merged head. The focused results below were obtained before this upstream merge.-D warnings) pass. Formatting andgit diff --checkpass.gpt-6.1-sol -> gpt-6-lunausing encrypted reasoning with visible summaries and original user input omitted. This revision was verified locally; the live service probe was not repeated. Full workspace CI was not run locally; hosted checks must run on the updated head.AI use
Tool(s) and scope: Codex implementation, sub-agent implementation/review and local verification.
Checklist
Does this PR entail a change in behavior?