Commit Graph
5 Commits
Author SHA1 Message Date
yetone bd5152ce3b sessions: a Codex rollout with nothing to change is only read, never written out again (#4735)
portRollout and repairLineages ran every rollout they looked at through
editRollout, which opened a temp file (and a zstd encoder for a packed
one) and wrote the whole rollout out before it could know whether any
line changed; a rollout with nothing to change was then thrown away. On
every pass over ~/.codex/sessions that was a full rewrite per file.

editRollout now reads first (eachEditedLine with no writer, which stops
at the first line that changes) and only then makes the temp file and the
encoder. If the second, writing pass changes nothing the file moved
between the reads and is held (errRolloutHeld), as a stat change already
was. The edit is built afresh per pass, so per-file state (portRollout's
"ours") starts over. Lines are read with ReadSlice into a 64KB buffer; a
longer line is gathered whole. The encoder is closed on every early
return now; it was left open before.

Run on mote (macOS 27.2), 10 rollouts of 4MB each with nothing to change:
- plain: 686ms -> 106ms per pass, 46MB -> 0.66MB allocated,
  232k -> 120 allocations.
- zst: 127ms -> 120ms per pass, 237MB -> 0.67MB allocated; the process's
  CPU (with the same setup) 2.55s -> 1.43s, sys 0.6s -> 0.17s.
- TestPortCodexRolloutsOnlyReadsWhatHasNothingToChange, plain and zst,
  with a 300KB line: nothing written out and the bytes the same; then
  with one line to change it is rewritten, the long line kept. With the
  reading pass taken out by hand it fails: "1 rollouts written out for
  nothing".
- TestPortCodex* and TestPortLine*: ok.
- go test ./internal/sessions ./internal/agent: ok (36.7s, 228.9s).
- GOOS=windows and GOOS=linux go vet of both: ok. gofmt -l: clean.

Not tried: a real ~/.codex/sessions pass in the app; the numbers are the
benchmark's, not a sample of the reporter's machine.
2026-11-01 17:41:02 +08:00
yetone 47173f593a sessions: a Codex thread left magpie keeps no reasoning OpenAI didn't seal
hentulong on X: after routing Codex through WorkBuddy and switching back,
Codex couldn't connect, and a fork said "Persisted response contains
hosted-tool, compaction, or unverifiable hidden reasoning state that
Rustponses cannot replay".

Cause: while Codex is routed through magpie to another vendor, the
reasoning items magpie hands it stay in the thread's rollout. After the
switch back Codex talks to chatgpt.com itself, and OpenAI refuses every
reasoning item it didn't seal. On the owner's real account:
- summary only, no encrypted_content: unsupported_persisted_item_context
  (the reporter's Rustponses error) on a previous_response_id
  continuation;
- with content (reasoning_text, what Codex 0.165 writes for DeepSeek via
  magpie): 400 array_above_max_length "Invalid 'input[5].content'";
- foreign encrypted_content: invalid_encrypted_content.
Codex treats each as fatal, so that thread and its forks fail while new
threads work. No stale config: Unwire/EndFailover drop openai_base_url.

Fix: when Codex is no longer routed or failing over (Unwire, quit,
uninstall and the periodic pass), PortCodexRolloutsLeft rewrites, in
threads begun on openai/magpie, every reasoning item (and every one in a
compacted line's replacement_history) whose encrypted_content isn't an
OpenAI Fernet token ("gAAAA") into type "magpie_reasoning", without id
and encrypted_content. Codex reads an unknown type as Other and never
sends it; magpie's sessions readers still show it. The edit keeps member
order and line length (same fitLine/lock path as the existing port),
has its own state entry, and starts at 2026-09-21. A survey of 150 live
rollouts found 340 of 340 OpenAI reasoning items in the gAAAA shape.

Run (mote, at f1d0c0bfd + this): go vet ./... for darwin, linux and
windows; go build for the three; go test -tags nogui -timeout 45m ./...:
every package ok but internal/gui, whose one red is
TestSettingsSaveKeepsWhatItDoesNotSend (SearchAll), open on main as #4514; gofmt -l clean.
Broken by hand: with the retire step off, and with Unwire passing false,
TestPortCodexRolloutsLeftRetiresUnsealedReasoning,
TestPortCodexRolloutsLeftKeepsItsOwnState and
TestCodexDisconnectRetiresMagpieReasoning go red.
Real Codex 0.165, sandbox CODEX_HOME, owner's account: a turn via magpie
with auto/deepseek-flash, then `codex exec resume` on gpt-6-sol direct
failed with array_above_max_length; after the left port the same resume
answered. The summary-only Rustponses refusal was reproduced with a
websocket probe against chatgpt.com and is retired by the same rule.

Not tried: the reporter's exact case in the interactive TUI (exec
resume doesn't warm up, so it never sends previous_response_id). A
thread Codex holds open keeps its in-memory history until reopened; a
switch not made through Unwire is caught by the periodic pass within
10 minutes.

Rebased after the full run onto 9551fadcb (5174c0970 GUI assets,
9551fadcb gateway/usage; no file here). At the pushed head:
go test -tags nogui -run Codex ./internal/sessions ./internal/agent ok,
go vet ./internal/sessions ./internal/agent ok.
2026-10-31 17:47:20 +08:00
yetone 67b12956ac sessions: a Codex rollout magpie rewrites keeps every line where it was
xybio (Discord #feedback): the Codex app often wouldn't reopen recent
threads: "invalid paginated history lineage for <id>: cutoff byte offset
is past the source rollout". Codex 0.162 keeps a fork's place in its
parent by byte (session_meta.history_base.end_byte_offset, checked by
rollout_lineage.rs validate_cutoff_bounds), and its state database keeps
turns and how far it has read by byte too. PortCodexRollouts (since
4896fc3ba, 10-21) wrote magpie's compaction item as Codex's summary
message, and since 79c8667c9 dropped Claude's sealed reasoning: both
shorter lines, so a parent shrank and every fork made before the pass
named a byte past its end.

Now every rewritten line keeps its length (fitLine): a shorter one is
padded with spaces after its JSON, which serde_json skips; a longer one
(a short summary under Codex's prefix) is left as it was in a paginated
rollout, and written as before in a legacy one, where Codex keeps no
place by byte. MoveCodexProvider, the sibling that rewrites session_meta,
pads the same way and refuses a longer provider id for a paginated
rollout. Forks already broken are repaired once per Codex home
(repairLineages): every line kept its count, and Codex names each line's
ordinal, so a fork's end_byte_offset is set again to where its parent's
line end_ordinal_exclusive-1 ends now, in a first line kept as long.

Run, at a47596ea6 plus this change:
- go test -count=1 ./internal/sessions/ ./internal/codexsummary/: ok;
  ./internal/agent/ -run 'Codex|Port|Move|Session': ok.
- gofmt -l internal/ clean; go vet ./internal/sessions/ ./internal/agent/,
  GOOS=windows and GOOS=linux go vet ./internal/sessions/: clean.
- Real, Codex 0.162.1 in a sandbox CODEX_HOME against a local mock
  Responses server that returns a magpie-claude1: reasoning item: codex
  exec made a paginated thread (50877 bytes), app-server thread/fork
  forked it, then a port pass. Old code: the parent went to 70570 bytes
  from 82912 and thread/resume and thread/read of the fork gave the
  reporter's exact error. New code: the parent kept 82912 bytes with no
  magpie-claude1: left, the fork resumed and read, the parent resumed,
  and codex exec resume ran a turn on the fork. A new-code pass over the
  old-code home repaired the fork (82912 -> 70570 in its history_base),
  after which it resumed and read.

Broken by hand:
- fitLine returning the rewrite as it is:
  TestPortCodexRolloutsKeepsBytePlaces red ("lines end at [... 11329],
  were at [... 14362]", the fork's offset past the end),
  TestPortCodexRolloutsLongerLine and TestMoveCodexProviderKeepsBytePlaces
  red.
- repairLineages a no-op: TestPortCodexRolloutsRepairsForks red.

Not tried: the Codex desktop app itself (the app-server it runs was);
a .zst parent against real Codex (the Go tests cover zst ports); Codex in
WSL, which the pass skips as before. The state database's turn offsets
for a parent already shrunk are left as they are; Codex 0.162.1 resumed
and forked such a parent in the sandbox.
2026-10-27 23:33:26 +08:00
yetone 79c8667c92 gateway: Codex gives Claude its signed thinking back through encrypted_content
Codex calling a Claude model through magpie (mysterious_dove_96933 on
Discord): a reply's reasoning items carried only the summary, so Claude's
thinking signature and a redacted_thinking block's data were gone. On
the next request of a tool loop magpie sent Anthropic the turn as
[tool_use] alone, with thinking on, which Anthropic documents as a 400
("final assistant message must start with a thinking block"), and the
model lost its reasoning across calls either way.

Now the Anthropic decoders name a signature as Claude's (KSig with
sealAnthropic, Part.SignedBy). The Responses encoder and renderResponses
give each thinking block a reasoning item whose encrypted_content is
"magpie-claude1:" and the block's JSON in base64 (internal/claudeseal):
its summary beside it, an empty summary for a block signed with no
text, and redacted_thinking as an item of its own. parseResponses reads
it back into the block as Claude wrote it, in order, so anthropicBody
sends it as before for an Anthropic client. A Gemini thought's
signature isn't named and isn't sealed.

The envelope never reaches a Responses API: withoutClaudeSeals in
passthrough and forwardOnce (the item keeps its summary, one with none
goes), codexInputAs leaves such an item out for Codex's own models, and
codexUpstreamOn takes it out before the ChatGPT backend. OpenAI's own
encrypted_content is untouched. sessions.PortCodexRollouts writes such
an item as its summary, so a thread resumed against OpenAI itself isn't
refused. redact.MaskJSON already keeps a reasoning item's seal whole
(no change); TestMaskJSONKeepsClaudeBlocks holds that.

Run, at 5e3dd1d52 plus this change:
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/sessions/
  ./internal/redact/ ./internal/claudeseal/: sessions, redact,
  claudeseal ok; gateway ok but for TestResponsesStreamToolThenHiddenThinking
  (#1786), whose hidden cases wanted no reasoning item, the loss this
  fixes. They now want one item carrying the sealed block with an empty
  summary, and its guarantee (a whole stream, no panic) is unchanged;
  re-run green.
- gofmt -l clean; go vet (darwin) on the touched packages, GOOS=linux
  go vet -tags nogui ./internal/..., GOOS=windows go vet on the touched
  packages: clean.
- TestCodexToolLoopGivesClaudeItsThinkingBack (a fake Anthropic: signed
  thinking, redacted_thinking, a text-less signed block, tool_use; a
  Codex-shaped request with store false and the encrypted_content
  include; then the follow-up) fails on 5e3dd1d52: "stream=true:
  Anthropic was sent 1 assistant blocks, want 4". Passes now, streamed
  and not.
- Real: a sandbox HOME with only OpenRouter's key (Anthropic endpoint,
  anthropic/claude-opus-5.5, served by Claude Platform on AWS), magpie
  serve on its own port, a Codex-shaped two-turn tool loop at effort
  high, streamed and not: turn 1 gave a reasoning item with
  magpie-claude1: (3.1KB), turn 2 was 200 through /v1/responses →
  /v1/messages and answered from the tool output.

Broken by hand:
- withoutClaudeSeals a no-op: TestClaudeBlocksNeverGoToAResponsesAPI
  red, the relay sent magpie-claude1: items.
- codexInputAs not leaving them out: red, "ChatGPT backend would be
  sent …".
- sealing any signature (no sealAnthropic check):
  TestGeminiSignatureIsNotSealedAsClaudes red.
- portValue's reasoning branch off: TestPortLineDropsClaudeBlocks red.

Not tried: the 400 itself. Through OpenRouter, Opus 5.5 answered turn 2
with the envelope stripped too (the old shape), so this route shows
only the lost reasoning, not the refusal. Not tried on api.anthropic.com
directly, Bedrock or Vertex keys, or Claude's subscription (whose tool
loop stays inside Claude Code's run). Codex resuming a ported thread
against OpenAI with such items wasn't run.
2026-10-27 11:26:54 +08:00
yetone 4896fc3ba1 codex: a thread magpie compacted goes on after magpie is quit or disconnected (LukeMa on X)
When magpie answers Codex's compaction itself (a magpie model, Codex's
own models through magpie's accounts, a CC Switch table), the item it
returns carries encrypted_content "magpie1:"+base64(summary). Codex keeps
it in the rollout (a response_item, and the compacted checkpoint's
replacement_history) and replays it with every later turn. Sent to the
ChatGPT backend directly, it is refused: "The encrypted content for item
cmp_magpie_1 could not be verified ... invalid_encrypted_content"
(probed with a real request on gpt-5.6-luna; the same summary as a user
message was answered).

Codex's remote compaction v2 keeps exactly one Compaction item, so magpie
can't answer with a plain message instead. sessions.PortCodexRollouts
writes each of magpie's items in a rollout as the message it stands for
(codexsummary.Message: Codex's summary prefix, a newline and the summary,
as a user message), which is what Codex's own local compaction stores and
what the gateway already sends in its place, so it reads the same through
magpie and goes on without it.

- Only magpie's compaction items change; other lines keep their bytes,
  the file its line count, mode and time. An unreadable one is left out
  of a list with its replacement_history_metadata entry, as Codex's own
  ghost-snapshot strip does.
- Published as Codex publishes a compressed rollout: temp file and
  rename, under thread-writer-locks/.coordination.lock and only with the
  thread's lock free. A thread a Codex has open is left for a later pass.
  A Codex home without thread-writer-locks is left alone.
- .jsonl.zst rollouts are read and written packed.
- Passes: 2 minutes after the GUI or magpie serve starts and every 10
  minutes; on Codex Disconnect (3s); as the GUI quits (3s). The first
  pass reads rollouts written since 2026-09-24; later ones only what
  changed since the last whole pass, plus what was left held
  (codex-portable.json in magpie's folder).

Run at this series' head (on origin/main 0fe039f14):
- Real codex 0.162.1, sandbox HOME/CODEX_HOME, exec </dev/null, against a
  fake upstream. In magpie mode it auto-compacted and the rollout's
  compacted line held magpie1:. In OpenAI mode, `exec resume --last`
  failed with "Error running remote compact task: ...
  invalid_encrypted_content". After PortCodexRollouts on that home, only
  that line changed (42 lines before and after). The same resume exited
  0, and the upstream saw the summary message.
- Broken by hand. With the thread-lock TryLock check off,
  TestPortCodexRolloutsLeavesAnOpenThread went red. With the replacement
  off, TestPortCodexRollouts went red. Both green with the fix restored.
- gofmt -l clean. go vet ./... (darwin) clean, GOOS=windows go vet
  ./internal/... clean, and GOOS=linux go vet -tags nogui ./... clean.
- go test ./... -count=1 -timeout 45m: 64 packages ok, two reds.
  - internal/agent ran out of time at 2706s (load average 25 to 57), the
    known #2723/#2544. Alone, go test ./internal/agent -count=1 is ok in
    901s.
  - internal/provider TestHoldReadsMigrationsOnce: "migrations.json read
    again while held" at 2.70s. It passes alone 5 of 5. I didn't touch
    that package. Filed #3095: heldFor (1s) can run out between the
    test's two reads.

Not tried:
- api.openai.com itself after a port. The refusal was probed on the
  ChatGPT backend, and the resume ran against a fake.
- A Codex in a WSL distro. Disconnect skips it, because its locks can't
  be taken from Windows.
- The Codex app still holding a thread when magpie quits. Its lock is
  held, so the file is left for the next pass, and the thread in that
  app's memory keeps the magpie1 item until it is loaded again.
2026-10-21 03:05:24 +08:00