Skip to content

feat(agent): unify ChatGPT encrypted state replay admission - #6654

Merged
M4n5ter merged 3 commits into
rust-previewfrom
feat/codex-state-replay
Nov 9, 2026
Merged

M4n5ter merged 3 commits into
rust-previewfrom
feat/codex-state-replay

Conversation

@me2seeks

@me2seeks me2seeks commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

ChatGPT subscription requests replay encrypted reasoning and native checkpoints across models, accounts and connections when the producing and consuming requests record matching comp_hash values. 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-preview and 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 0a5ce771a9 is 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 because agent-client-protocol 5.0.0 is 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.

  • Five replay integration tests pass, including an eight-case compatibility matrix using one Root/Engine with distinct sessions, actual 429 retry request equality, plaintext summary preservation without ciphertext, cross-account native replay/re-compaction and one physical reopen.
  • The existing handoff/compaction/retry scenario passes with a sealed old hash/timestamp and a refreshed hash/timestamp after Engine restart; subsequent logical requests record the refreshed context. Native Owner assembly is compiled and inspected; a separate real OAuth/Host-restart fixture was not added.
  • Existing native-compaction integration: 7 passed. Persisted directory codecs/scanning: 8 passed with the original byte guard. EventLog compaction/source/frozen proofs: 15 passed. Resident/backed history consistency: 1 passed.
  • Native library check and Engine/EventLog all-target Clippy (-D warnings) pass. Formatting and git diff --check pass.
  • The hand-assembled opaque frozen-request fixture was removed; actual execution/wire retry behavior provides the regression coverage. Repeated cold Root/Engine startups were removed from the matrix instead of increasing its timeout.
  • Earlier live subscription arithmetic control verified gpt-6.1-sol -> gpt-6-luna using 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

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope: Codex implementation, sub-agent implementation/review and local verification.

Checklist

  • Tests cover the change and fail without it
  • Format, typecheck and the affected suites pass locally

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No

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 M4n5ter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.context freezes CodexRequestProvenance including CodexCompatibility { comp_hash, fetched_at }.
  • CodexInventory (plugins/agent/native/src/model/codex_inventory.rs:39-40) is in-memory only, refreshes after REFRESH_AT = 270s, and expires at MAX_AGE = 300s. Across any host restart (the primary handoff boundary) or after 4.5 minutes in-process, resume_goal_handoff calls prepare_frozen_retry -> source.capture(), producing settings.context with a new fetched_at (or compatibility: None / a rotated comp_hash) and passing context: settings.context into RunWork::Handoff.
    • Even when comp_hash is unchanged, CodexCompatibility derives PartialEq over fetched_at (plugins/agent/facts/src/context.rs:133-139), so Engine::start_model (engine/src/lib.rs:681: input.context != pause.execution.context) fails with RunError::InvalidInput("handoff execution settings changed").
    • If comp_hash rotated or compatibility expired to None, continuation::inspect (continuation.rs:145-210) projects history under the new input.context, drops prior reasoning items, and fails replay != pause.execution.replay with RunError::InvalidInput("handoff admission replay changed after sealing").
    • In both cases, goal/dispatch.rs:187-211 treats RunError::InvalidInput(_) as a user settings change, cancels the handoff, and calls saved.goal.pause_for_settings(), stopping the active /goal loop even though the user changed nothing.
  • Relatedly, steps.rs:238 mutates *input = frozen_input; when rehydrating a retry. If that retried step finishes and the next loop iteration enters handoff.boundary (steps.rs:263-323) before input.refresh_model (steps.rs:344), HandoffPause seals 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_source refresh for subsequent steps, and avoid leaking retry-only frozen_input overrides into the next step's handoff boundary), and add a handoff test where fetched_at and comp_hash advance 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 in platform/event-log; maka-agent-engine (model_attempt.rs:203) writes it into selection only to read it back from captured.selection().model in prepared.rs:279, 547 and backed.rs:108. Pass target model / replay parameters directly inside maka-agent-engine (history::prepared::capture / ProjectContext) instead of extending maka_event_log::context::semantic::SemanticSelection.
  • Per-part provenance duplication on the write/scan hot path: Replay admission only inspects TextKind::Thinking parts and only depends on whether the producer was Codex plus its optional comp_hash (connection_id, account_id, and fetched_at are never consulted). Cloning the entire Option<CodexRequestProvenance> onto every SemanticKind::AssistantPart (without skip_serializing_if = "Option::is_none", emitting "codex":null into row_json for every text/tool-call/tool-result part across all providers) and SHA-256 hashing it into every RowDirectory::AssistantPart duplicates unused provenance on every part. Either derive producer replay basis from the step's ModelRequested fact or record only minimal Codex replay basis where needed.
  • Broken persisted RowDirectory layout & edited guard fixture: directory.rs:22-24 and codec/tests.rs:287-288 explicitly document that RowDirectory Postcard bytes are persisted in context_semantic_rows.directory_bytes and require a migration/rebuild if changed. Inserting codex into RowDirectory::AssistantPart in place without rebuilding directory_bytes—and updating the hex fixture in frozen_rowdirectory_bytes_keep_their_meaning (codec/tests.rs:304-307)—causes existing SQLite sessions containing assistant_part rows (source_sequence >= 2) to fail codec::decode with "invalid directory descriptor". Any persisted descriptor change must come with a clean storage rebuild/migration (like 0017_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 reasoning items decode both visible summary_text into text and encrypted state into provider_options (plugins/agent/provider-protocol/src/responses/decode.rs:524-552).
  • When switching from standard OpenAI Responses (codex: None) to ProviderKind::OpenResponses(PlaintextContent) (source_projector.rs:510-517) or ProviderKind::OpenaiChatCompletions (plugins/agent/model/src/adapters/wire/chat_source.rs:428-433), OpenAI encrypted provider_options are stripped/ignored while the visible plaintext text is replayed.
  • Returning ProjectedRow::Skip at source_projector.rs:192-201 before project_text whenever codex.is_some() && target.codex.is_none() drops the visible plaintext reasoning summary even for targets that never replay reasoningEncryptedContent. Only encrypted OpenAI replay (ProviderKind::OpenaiResponses / provider_options) needs to be gated; plaintext-capable targets should strip incompatible provider_options rather than dropping non-empty text.

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_restart runs an 8-iteration loop that performs 16 serial cold SessionFixture::open (all SQLite migrations + WAL fsyncs) and CodeExecutor startups inside a hardcoded 90s tokio::time::timeout. Running this single test solo locally exceeds 90s (90.06s) and panics with Elapsed(()); running the 4 codex_replay tests together also pushes compatible_native_switch_replays_and_recompacts_across_accounts_after_restart past its 45s timeout. Reuse one RootFixture/Engine across distinct session IDs for the compatibility matrix, reserving physical reopen for a single dedicated persistence check.
  • codex_replay.rs:35-38 hardcodes fetched_at: 1 everywhere, masking the catalog-refresh handoff bug above.
  • In frozen_request/tests.rs:232-520, avoid hand-assembling raw ModelRequested/ModelCompleted facts in a for seed in [true, false] loop and walking internal PreparedPrompt recipe 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 冷启动,并硬编码 90s tokio::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 事件并递归遍历内部 PreparedPrompt recipe 树(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 Astro-Han 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.

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(

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.

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.

Merge upstream 0a5ce77 and adapt the producer-context reader to the synchronous SQLite API. Engine and test-target offline compilation passes.

Refs #6579

Generated-by: Codex

@Astro-Han Astro-Han 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.

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.

@M4n5ter
M4n5ter merged commit 1cba85e into rust-preview Nov 9, 2026
34 of 37 checks passed
@M4n5ter
M4n5ter deleted the feat/codex-state-replay branch November 9, 2026 03:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/L Under 1000 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants