gateway: a Codex conversation compacted natively is held to its account only when native compaction is on, and told why when it can't go there (#2642, #2582)

ScarfQian (#2642, still on v0.1.1279): after a native compaction by one
Codex account, routing to another answered 400 "only that key or account
can read the compaction it sealed ... switched off, removed, or no longer
serves". Three causes, one fix each:

- #2582 (Dony2050, ump45nose's patch): one of Codex's own models asked on
  the backend path through magpie's accounts (codexAccounts) kept the
  compaction_trigger whatever the codex provider's native compaction
  setting, so every compaction was sealed by and recorded to one account.
  It is now decided as a magpie model's is: codexInputAs with
  nativeCompactionFor("codex/<model>"); off (the default) gives
  codexCompact's magpie1: summary, which any account reads, and records
  no writer. Unlike ump45nose's branch, /responses/compact and Codex's
  own single sign-in relay are left as they were: the legacy endpoint's
  body has no trigger for codexCompact to answer, and a lone sign-in has
  no other account to move to.
- ggbdpq's fix (0ab41eba0, e1646488d, ported as is): a writer whose own
  model list has since dropped the model sat in planned.left, out of the
  candidates, so checkpointReaders never found it and refused although it
  was on. It is now taken back from planned.unlisted (plan, planLevel and
  the nested weighted plan), its row moved from left to order.
  sealedReaders, run before it for a sealed subagent task, narrows
  unlisted too (sibling).
- A request carrying a recorded seal while only Codex's own sign-in is on
  was relayed as it came (codexAccounts false), so with the writer
  switched off the one account left was sent it. codexSealedFor routes
  it through serve, where checkpointReaders holds it to the writer.
- checkpointError now says the reason magpie's settings give
  (checkpointGone: provider removed, account signed out, sign-in lapsed,
  paused while others are on, switched off, kept from the model in Names &
  levels, key off or gone, model disabled, or the model/group asked for
  not routing to it), the fix for that reason, and whether native
  compaction is on for the writer's provider now. The old catch-all
  sentence is gone.

The seal is still treated as readable only by the account that wrote it,
as #1099 and #2271 found; chestnutLeeeee's report that another account read
one in a direct canary was not tried here (no real accounts).

Tests (fake ChatGPT backend, sandbox HOME, nothing on the network):
TestCodexOwnModelCompactionHonoursTheToggle (off: summary, no trigger
upstream, no writer; on: native seal kept, writer recorded),
TestNativeCompactionWriterGoneSaysWhy (spare switched off, own paused,
Names & levels, signed out), ggbdpq's
TestNativeCompactionWriterWhoseListLacksTheModel and
...ThroughAGroupWhoseListLacksTheModel. All four are red on 7660399a1.
Broken by hand on this change, each went red: codexInputAs back to
(false,false) -> Toggle; codexSealedFor not called -> spare switched off;
the unlisted loop emptied -> both WhoseList tests; the Paused case
skipped -> own paused.

TestProtectionRefusalAskedOnceNobodyRests (vs's 502 "response protection
is unavailable" on a bare gpt-5.5 compaction through three accounts) was
about the native path, which that model now takes only with native
compaction on; it turns it on (nativeOn). Off, the compaction is magpie's
summary, as TestProtectionRefusedCompactionAsText already covers.

Run at this change on 7660399a1: gofmt -l clean; go vet ./... (darwin),
GOOS=linux and GOOS=windows go vet -tags nogui ./... ok;
full go test -tags nogui -timeout 45m ./... (load average ~140): every
package ok except internal/agent and internal/gateway, which ran past 45m
(#2544, #2108), and TestProtectionRefusalAskedOnceNobodyRests, mine,
fixed above. Then each alone: internal/gateway -timeout 45m finished in
2345s with one red, TestTranslatedStreamKeepsClientAlive/responses_to_chat
(a keepalive timing test under load, passes alone; filed as #2711, sibling
of #2169); internal/agent -timeout 100m ok in 2115s. The protection,
compaction and Codex tests (-run 'TestProtection|Compact|Compaction|TestCodex')
ok after the test change.
No GUI file changed. Not tried against the real ChatGPT backend.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
Co-authored-by: ump45nose <52391318+ump45nose@users.noreply.github.com>
This commit is contained in:
yetone
2026-10-17 18:19:51 +08:00
co-authored by ggbdpq ump45nose
parent bad4508c4f
commit bf931f82c3
7 changed files with 421 additions and 16 deletions
+1 -1
View File
@@ -139,7 +139,7 @@ recorded as a prediction failure (`noPrediction`).
- Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models kept out of agents' lists for routing groups (`provider.CodexNativeUnlisted`) are dropped from it too, hidden ones kept: every one when the codex provider is "Only through routing groups" (`Provider.Unlisted`), and those a group that unlists its members names (`Group.Unlists`). A Codex there only for failover keeps them, as it is handed no groups; `spawnChoices` drops the same ones (#1602, `TestCodexModelListUnlistedForGroups`).
- Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming Messages request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (`Part.Sealed`, `SealedBy`; events `KThinkStart`, `KSealed`, `KTextSig` in [`ir.go`](../../internal/gateway/ir.go)), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (`sealedBy`). Anthropic's `redacted_thinking` goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (`aBlock` still writes `"thinking": ""`, #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and `encrypted_content`, and goes back to a Responses upstream as it came when it has no reasoning text (`sealedReasoning`; text, another vendor's, is still left out for OpenAI, #1411). Gemini's `thoughtSignature` stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets `skip_thought_signature_validator`. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (`__ts<n>__`), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. The signature itself is kept in magpie's folder, `gemini-signatures/<key>`, named by its hash (`keepSignature` in [`gemini_sigstore.go`](../../internal/gateway/gemini_sigstore.go)), and the id carries only the key (`__tsk16__<key>`), so an id stays under 64 characters however long the step's signature (#2411: LobeHub's PostgreSQL index turned away a 3KB id). A key magpie no longer has, or whose file doesn't hash to it, reads as no signature; one not read for 90 days is removed. Where the folder can't be written, the id carries the signature as before. Carrying reasoning across APIs (an envelope) isn't done.
- A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them; any other upstream's reasoning becomes items magpie made: an `rs_` id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (`withoutBareReasoning`) unless `store` is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (`refusesInput`: `param` is `input`, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, `passthrough` asks once more without them and, once that works, leaves them out for that provider and model from then on (`bareReasoningRefused`, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. When a provider answers its summary request 404, or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). So does the ChatGPT backend's 502 "response protection is unavailable" (`protectionRefused`): a long history refused so was answered as text. Codex also compacts remotely, a `compaction_trigger` on `/responses` that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at `/v1` while a magpie model is on, so `handle` makes the summary there too (`codexInput`, `codexCompact`), and magpie's summaries go back to the model as text (#1301). A summary is wanted only whole (`askWhole`, `holdWriter.wantWhole`): its stream is held to its end, not let through at its first words, so a reply cut short (`errEndedShort`), failed halfway (a 429 "Individual quota reached" after some of it) or ended `incomplete` (`endedIncomplete`, `incompleteReply`) fails over to the next candidate like a failure before any of it, and rests the account as that failure would; one that reached its output limit rests nobody. With nobody left, `codexCompact` answers 502 and never hands Codex the words before the cut as the summary (#2274, huangzuomin: Antigravity cutting each summary short). Codex with context_management's experimental mode compacts in the background at every step while the conversation is over its threshold and drops a failed compaction without a word, so a conversation whose summaries keep failing is asked again every few seconds, each paying for the whole history (1169 compactions in 6 hours there). After `compactFailsMost` (3) failed summaries in a row of one conversation (`prompt_cache_key`) on one model, each within `compactHeldFor` (5 minutes) of the last, the next is answered at once with a 400 naming the last failure, which Codex doesn't ask again, and no model is asked until 5 minutes have passed (`compactFails` in [`codex_compact_guard.go`](../../internal/gateway/codex_compact_guard.go)); a summary that comes clears the count, and a sign-in's 401 or 403 isn't counted. `TestCodexCompactCutSummaryFailsOver`, `TestCodexCompactCutSummaryIsNoSummary`, `TestCodexCompactKeepsFailingIsHeld`.
- Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set <id> compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; `TestNativeCompactionFallbackSealStaysWithItsWriter`). It is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); with the writer gone from the candidates (switched off, resting, removed), magpie answers 400 `checkpointError` naming why, and never sends it to another key, drops it, or summarises it in its place. With the writer held at its usage cap or for credits it may not spend, the answer is 429 `checkpointCappedError` (record `checkpointCappedRecord`, "native compaction's account at its usage cap"), naming that account, that the others serving the model weren't tried for the compaction, and that neither the routing mode nor how conversations stay changes that: wait for the window, raise or lift its cap, or start a new conversation (#2517, lm0711; before, it read "every account at its usage cap" though another had room; `TestNativeCompactionWriterAtItsCap`). `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`.
- Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set <id> compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; `TestNativeCompactionFallbackSealStaysWithItsWriter`). It is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); a writer whose own list has since dropped the model is tried still, as the last resort an account whose list lacks the model is — it sealed the model's compaction, and no other can read it (`planned.unlisted`, `TestNativeCompactionWriterWhoseListLacksTheModel`, #2642: it was refused as "switched off, removed, or no longer serves" though it was on, and switching it on changed nothing). With the writer gone from the candidates, magpie answers 400 `checkpointError` with the reason its settings give (`checkpointGone`: the provider removed, the account signed out, its sign-in lapsed, paused while others are on, switched off, kept from the model in Names & levels, the key off or gone, the model disabled, or the model or group asked for not going to it), what lets the conversation go on, and whether native compaction is on for the writer's provider now, and never sends it to another key, drops it, or summarises it in its place (`TestNativeCompactionWriterGoneSaysWhy`). One of Codex's own models asked on the backend path is decided as a magpie model is when magpie's Codex accounts serve it (`codexAccounts`): the trigger is kept only with the codex provider's native compaction on, else `codexCompact` gives magpie's summary, which any account reads, and no writer is recorded (#2582, ump45nose; before, every such compaction was sealed natively whatever the setting, and the conversation was held to its account; `TestCodexOwnModelCompactionHonoursTheToggle`). Codex's own sign-in alone, relayed as it came, still compacts natively, unrecorded, as does `/responses/compact`; but a request carrying a compaction magpie recorded the writer of goes through routing even then (`codexSealedFor`), so with the writer switched off the one account left isn't sent it. With the writer held at its usage cap or for credits it may not spend, the answer is 429 `checkpointCappedError` (record `checkpointCappedRecord`, "native compaction's account at its usage cap"), naming that account, that the others serving the model weren't tried for the compaction, and that neither the routing mode nor how conversations stay changes that: wait for the window, raise or lift its cap, or start a new conversation (#2517, lm0711; before, it read "every account at its usage cap" though another had room; `TestNativeCompactionWriterAtItsCap`). `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`.
- A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (`passthrough`): Responses Lite's `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set `codexAsSent` (`magpie provider set <id> codex=as-sent`) gets a request from Codex (`fromCodex`) as Codex sent it, its model name alone swapped, with Codex's own headers (`codexClientHeader`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`.
- A tool a Chat request's message carries joins the request's `tools` (`liftMessageTools` in [`message_tools.go`](../../internal/gateway/message_tools.go), #2322). Pi with `supportsMidConvoToolAdditions` gives a tool it adds mid-conversation as `{"role":"system","tools":[…]}` with no content, and keeps top-level `tools` as they were at the start; no Chat API reads tools there, and `parseChat` read only the top-level ones, so the tool could be called on no route. `handle` lifts them for every Chat body before `serveAgent`, so the Chat relay, the schema fixers, redaction (the tool is a tool definition, not message text), the prompt shown and routing all see them; `parseChat` lifts too, for a body that never came through `handle` (the Claude subscription bridge's direct callers). Each tool joins once by name and the first definition wins: a top-level tool keeps its own, then the earliest message's, as `liftAdditionalTools` and a `tool_addition` (`withoutDeferredTools`) do. A system or developer message that carried only tools is left out, so it is neither relayed as an empty system message nor joined into the system text as an empty part; one with content keeps its place without `tools`. Messages stay where they are: the in-place system message the issue also asks for is not this change. `TestPiAddedToolReachesEveryRoute` sends deephbz's Pi 1.2.0 bytes through the Chat relay, Messages, Responses, Gemini and Codex, and `TestPiAddedToolOfferedToClaudeCode` through the Claude subscription bridge.
- A Chat request's tool in another API's shape is put in the Chat shape, `{"type":"function","function":{name, description, parameters, strict}}` (`shapeChatTools` in [`chat_tool_shape.go`](../../internal/gateway/chat_tool_shape.go), #2622, jinyue806): MCP's `{"name","description","inputSchema"}` (ZCode), Anthropic's `input_schema`, a bare `{"name","parameters"}` and Responses' flat `{"type":"function","name",…}`. No Chat API takes those (SenseNova: "field Tools[0].Type invalid, should be set" and "function cannot be empty"), and `parseChat` read no name from them, so a translated request offered a tool named "". It runs right after `liftMessageTools`, in `handle` for every Chat body and in `parseChat`, so it holds for every Chat upstream, not SenseNova's alone. A tool with its `function`, a hosted tool (any other `type`) and one with no name are left as they came, and a request with none to shape is relayed byte for byte. `TestChatToolInAnotherShapeIsShaped` sends the report's request with each of its four tools through the Chat relay, Messages and Responses; `TestShapeChatToolsLeavesChatShape`.
+52 -4
View File
@@ -177,11 +177,27 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {
}
break // preserve native compaction's existing passthrough
}
body, _ = codexInput(body, false)
if id, ok := codexAccounts(r, model); ok {
s.serveAgent(w, r, provider.Responses, withModel(body, id))
id, ok := codexAccounts(r, model)
if !ok {
id, ok = codexSealedFor(r, model, body)
}
if ok {
// through magpie's accounts, Codex's compaction is the codex
// provider's to decide as a magpie model's is: sealed natively
// only with its native compaction on, as only the account that
// sealed it can read it; off, magpie's summary, which any of
// them reads (#2582, #2642: one of Codex's own models compacted
// natively whatever the setting, and the conversation was held
// to that account)
body, compact := codexInputAs(withModel(body, id), true, s.nativeCompactionFor(id))
if compact {
s.codexCompact(w, r, body)
return
}
s.serveAgent(w, r, provider.Responses, body)
return
}
body, _ = codexInput(body, false)
if r.Header.Get(AccountHeader) != "" {
// relayed as it came, it would go to Codex's own sign-in only
writeError(w, provider.Responses, 400, AccountHeader+" names one of magpie's Codex accounts, and Codex isn't signed in to ChatGPT here with any on in magpie")
@@ -277,7 +293,7 @@ func (s *Server) sealedReader(p provider.Provider, model string, sealers []strin
}
// sealedReaders keeps of cands those that can read a sealed subagent task,
// pl's order with them.
// pl's order, held, capped and unlisted with them.
func (s *Server) sealedReaders(cands []candidate, pl planned, sealers []string) ([]candidate, planned) {
var kept []candidate
var order []Weighed
@@ -290,6 +306,17 @@ func (s *Server) sealedReaders(cands []candidate, pl planned, sealers []string)
cands, pl.order = kept, order
pl.held = slices.DeleteFunc(slices.Clone(pl.held), func(c candidate) bool { return !s.sealedReader(c.p, c.model, sealers) })
pl.capped = slices.DeleteFunc(slices.Clone(pl.capped), func(c candidate) bool { return !s.sealedReader(c.p, c.model, sealers) })
// the accounts whose list lacks the model, which a native compaction's
// writer is taken back from (checkpointReaders), are narrowed alike
var unlisted []candidate
var unlistedW []Weighed
for i, c := range pl.unlisted {
if s.sealedReader(c.p, c.model, sealers) {
unlisted = append(unlisted, c)
unlistedW = append(unlistedW, pl.unlistedW[i])
}
}
pl.unlisted, pl.unlistedW = unlisted, unlistedW
return cands, pl
}
@@ -668,6 +695,27 @@ func codexAccounts(r *http.Request, model string) (string, bool) {
return id, true
}
// codexSealedFor is codexAccounts for a request magpie would relay as it
// came to Codex's own sign-in, the one account on, that carries a native
// compaction magpie recorded the writer of: it goes through routing,
// which sends it only to that writer or answers why not
// (checkpointReaders, checkpointError). Relayed, it reached the sign-in
// whoever sealed it, and was refused there (#2642: the account that
// compacted it switched off, the one left was sent it).
func codexSealedFor(r *http.Request, model string, body []byte) (string, bool) {
if model == "" || strings.Contains(model, "/") || apiKey(r.Header) {
return "", false
}
if _, sealed := checkpointOf(body); !sealed {
return "", false
}
id := "codex/" + model
if p, _, ok := provider.Resolve(id); !ok || p.Account == nil || p.Account.Agent != "codex" {
return "", false
}
return id, true
}
// withModel is a request body asking for another model.
func withModel(body []byte, model string) []byte {
var q map[string]json.RawMessage
+6
View File
@@ -357,6 +357,8 @@ func (s *Server) plan(p provider.Provider, model string, from provider.Protocol)
w := weighed(c, q, weighing{}, fallback, from)
w.Unlisted = true
pl.left = append(pl.left, w)
pl.unlisted = append(pl.unlisted, c)
pl.unlistedW = append(pl.unlistedW, w)
}
return cs
}
@@ -450,6 +452,8 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.
w := weighed(c, m.Provider, weighing{}, false, from)
w.Unlisted, w.Via = true, m.Groups()
pl.left = append(pl.left, w)
pl.unlisted = append(pl.unlisted, c)
pl.unlistedW = append(pl.unlistedW, w)
}
return cs
}
@@ -485,6 +489,8 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.
cs, sub.order = sinkOwn(m.Via[depth], cs, sub.order)
pl.left = append(pl.left, sub.left...)
pl.capped = append(pl.capped, sub.capped...)
pl.unlisted = append(pl.unlisted, sub.unlisted...)
pl.unlistedW = append(pl.unlistedW, sub.unlistedW...)
if len(cs) > 0 {
add(unit{cs: cs, order: sub.order, member: m.Path[depth]}, firstAwake(cs))
}
+122 -10
View File
@@ -6,11 +6,13 @@ package gateway
// as it came, sealed (encrypted_content), not as magpie's "magpie1:"
// summary. Only the key or account that sealed it can read it again, so
// magpie remembers who wrote each one (compactions.json, beside
// affinity.json), and a later request carrying it goes only there. When
// that one can't be asked — switched off, removed, out of the group —
// the request is refused, saying why: the compaction is never sent to
// another to be refused, dropped (withoutCompaction), or summarised in its
// place, which would lose the conversation's earlier context unasked.
// affinity.json), and a later request carrying it goes only there — a
// writer whose own list has since dropped the model included, tried as
// the last resort an account whose list lacks the model is. When that one
// can't be asked — switched off, removed, out of the group — the request
// is refused, saying why: the compaction is never sent to another to be
// refused, dropped (withoutCompaction), or summarised in its place, which
// would lose the conversation's earlier context unasked.
import (
"bytes"
@@ -278,9 +280,40 @@ func saveCheckpoints() {
}
// checkpointReaders keeps of cands those of the key or account who, pl's
// order with them; left says one is left, if only held or capped.
// order with them; left says one is left, if only held or capped. One
// whose own list lacks the model now (planned.unlisted) is kept too: it
// is tried as the last resort an account whose list lacks the model is,
// and none other can read what it sealed. Its row goes from left to the
// order with it, so the Routing page doesn't tell it both tried and
// unlisted, skipped.
func checkpointReaders(cands []candidate, pl planned, who string) (_ []candidate, _ planned, left bool) {
return keepCandidates(cands, pl, func(c candidate) bool { return c.who() == who })
kept, pl, ok := keepCandidates(cands, pl, func(c candidate) bool { return c.who() == who })
if ok {
return kept, pl, true
}
var found []candidate
var ws []Weighed
for i, c := range pl.unlisted {
if c.who() != who {
continue
}
found = append(found, c)
w := pl.unlistedW[i]
w.Unlisted = false // it is asked, as the conversation's only reader
ws = append(ws, w)
}
if len(found) == 0 {
return nil, pl, false
}
// the rows it goes to order with: they leave left, or the Routing page
// would have it both tried and unlisted, skipped
asked := make(map[string]bool, len(ws))
for _, w := range ws {
asked[w.ID] = true
}
pl.left = slices.DeleteFunc(pl.left, func(w Weighed) bool { return asked[w.ID] })
pl.order = append(pl.order, ws...)
return found, pl, true
}
// checkpointHeld is, of held, the key or account that sealed the native
@@ -327,10 +360,89 @@ func keepCandidates(cands []candidate, pl planned, keep func(candidate) bool) ([
}
// checkpointError is what Codex is told when the compaction a request
// carries was sealed by a key or account the request can't go to now.
// carries was sealed by a key or account the request can't go to now:
// why, as magpie's own settings say, and what lets the conversation go on
// (#2642: it said "switched off, removed, or no longer serves" of an
// account that was on, and "switch it on again" changed nothing).
func checkpointError(model string, cp checkpointWriter) string {
return fmt.Sprintf("This conversation was compacted natively by %s, and only that key or account can read the compaction it sealed. The request for %s can't go to it now: it is switched off, removed, or no longer serves %s. magpie doesn't send the compaction to another, which would refuse it, nor drop it or summarise it in its place, which would lose the conversation's earlier context. Switch %s on again for %s to go on with this conversation, or start a new one.",
cp.Who, model, model, cp.Who, model)
what := "account"
if strings.Contains(cp.Who, "#") {
what = "key"
}
why, fix := checkpointGone(model, what, cp)
msg := fmt.Sprintf("This conversation was compacted natively by %s: the compaction is sealed (encrypted) to that %s, and no other key or account can read it. The request for %s can't go to it now: %s. magpie doesn't send the compaction to another, which would refuse it, nor drop it or summarise it in its place, which would lose the conversation's earlier context. To go on with this conversation, %s; or start a new conversation.",
cp.Who, what, model, why, fix)
if p, err := provider.Find(cp.Provider); err == nil {
if p.NativeCompaction {
msg += fmt.Sprintf(" Native compaction is on for %s, so each conversation it compacts is held to the %s that compacted it; turned off (the provider's Compaction row), magpie summarises instead, which any of them can read.", p.ID, what)
} else {
msg += fmt.Sprintf(" Native compaction is off for %s now, so a compaction magpie routes among its %ss is magpie's summary, which any of them can read.", p.ID, what)
}
}
return msg
}
// checkpointGone is why the key or account that sealed cp can't be asked
// for model, and what would let it be: removed, signed out, its sign-in
// lapsed, paused or switched off, the model kept from it, or the model or
// group asked for not going to it. The capped and the held are told
// checkpointCappedError's instead.
func checkpointGone(model, what string, cp checkpointWriter) (why, fix string) {
p, err := provider.Find(cp.Provider)
if err != nil {
return fmt.Sprintf("the provider %s is no longer in magpie", cp.Provider),
fmt.Sprintf("add %s again with that %s", cp.Provider, what)
}
served := cp.Model
if served == "" {
served = model
}
if _, off := provider.ModelDisabled(p.ID, served); off {
return fmt.Sprintf("%s/%s is disabled", p.ID, served), fmt.Sprintf("enable %s/%s again", p.ID, served)
}
if _, kid, isKey := strings.Cut(cp.Who, "#"); isKey {
for _, k := range p.KeyList() {
if k.ID != kid {
continue
}
switch {
case !k.On:
return fmt.Sprintf("that key of %s is switched off", p.ID), "switch it on again in the provider's keys"
case !p.AccountServes(kid, served):
return fmt.Sprintf("that key is set not to serve %s (Names & levels)", served), fmt.Sprintf("let it serve %s again", served)
}
return checkpointNotRouted(model, served)
}
return fmt.Sprintf("that key is no longer one of %s's", p.ID), fmt.Sprintf("add the same key to %s again", p.ID)
}
user := strings.TrimPrefix(cp.Who, cp.Provider+"@")
agent := cp.Provider
if p.Account != nil && p.Account.Agent != "" {
agent = p.Account.Agent
}
for _, l := range provider.Logins(agent) {
if !strings.EqualFold(l.User, user) {
continue
}
switch {
case l.Lapsed != "":
return "its sign-in has lapsed", fmt.Sprintf("sign in to %s again in magpie", l.User)
case l.Paused:
return "it is paused, passed over while magpie's other accounts are on", fmt.Sprintf("turn %s on again: the others can stay on beside it, and only this conversation is held to it", l.User)
case !l.On:
return "it is switched off in magpie", fmt.Sprintf("switch %s on again: the others can stay on beside it, and only this conversation is held to it", l.User)
case !p.AccountServes(l.User, served):
return fmt.Sprintf("it is set not to serve %s (Names & levels)", served), fmt.Sprintf("let %s serve %s again", l.User, served)
}
return checkpointNotRouted(model, served)
}
return fmt.Sprintf("%s is no longer signed in to magpie", user), fmt.Sprintf("sign in to %s again in magpie", user)
}
// checkpointNotRouted is checkpointGone for a writer that is on and may
// serve the model: what was asked for doesn't go to it.
func checkpointNotRouted(model, served string) (why, fix string) {
return fmt.Sprintf("%s doesn't route to it (another model, or a routing group it isn't in)", model), fmt.Sprintf("ask for %s, which it compacted, through a route that has it", served)
}
// carrierError is what Codex is told when its compaction_trigger, asked
+229
View File
@@ -8,6 +8,7 @@ import (
"sync"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
@@ -310,3 +311,231 @@ func TestNativeCompactionWriterAtItsCap(t *testing.T) {
t.Fatalf("no compaction: %d %s", code, body)
}
}
// A conversation compacted natively by an account whose own list has since
// dropped the model goes to it still: only it can read the compaction, and
// an account whose list lacks the model is the last resort tried when none
// lists it (perKeyBarred). The other account, whose list has the model, is
// never sent it. (#2642: the request was refused saying the writer is
// "switched off, removed, or no longer serves" though it is on, and the
// advice to switch it on again changed nothing.)
func TestNativeCompactionWriterWhoseListLacksTheModel(t *testing.T) {
codexSignedIn(t, "spare@example.com")
b := newResetBackend(t)
// the spare's plan lists the model; the writer's no longer does
if err := catalog.SaveLive("codex@"+provider.KeyID("spare@example.com"), provider.CodexBase, []catalog.Model{{ID: "gpt-5.5"}}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("codex@"+provider.KeyID("me@example.com"), provider.CodexBase, []catalog.Model{{ID: "gpt-4.1"}}); err != nil {
t.Fatal(err)
}
wroteCheckpoint("gAAAAB-sealed-by-me", candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{User: "me@example.com"}}})
srv := New()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":[{"type":"compaction","encrypted_content":"gAAAAB-sealed-by-me"},{"type":"message","role":"user","content":[{"type":"input_text","text":"go on"}]}]}`))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
srv.Handler().ServeHTTP(rec, req)
code, body := rec.Code, rec.Body.String()
tried, _ := b.seen()
if code != 200 || tried != "acct-1" {
t.Fatalf("%d tried %q: %s", code, tried, body)
}
if !strings.Contains(body, "pong") {
t.Errorf("the writer's answer: %s", body)
}
if strings.Contains(tried, "acct-2") {
t.Errorf("the spare, whose list has the model, was asked: %q", tried)
}
// tried, its row leaves the routing page's left: not both attempted
// and unlisted, skipped
for _, w := range lastRoute(srv).Left {
if w.Who == "me@example.com" {
t.Errorf("the writer, tried, still left out: %+v", w)
}
}
}
// The same through a routing group: the conversation's model is the group,
// whose member is the codex provider, so the plan is planLevel's keys, not
// plan's add, and the writer whose own list has since dropped the model is
// tried still, the spare never asked. (#2642: keys kept the left-out
// writer's row alone, so a request routed through the group was refused
// 400 all the same.)
func TestNativeCompactionWriterThroughAGroupWhoseListLacksTheModel(t *testing.T) {
codexSignedIn(t, "spare@example.com")
b := newResetBackend(t)
// the spare's plan lists the model; the writer's no longer does
if err := catalog.SaveLive("codex@"+provider.KeyID("spare@example.com"), provider.CodexBase, []catalog.Model{{ID: "gpt-5.5"}}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("codex@"+provider.KeyID("me@example.com"), provider.CodexBase, []catalog.Model{{ID: "gpt-4.1"}}); err != nil {
t.Fatal(err)
}
nativeOn(t, "codex")
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"codex/gpt-5.5"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
wroteCheckpoint("gAAAAB-sealed-by-me", candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{User: "me@example.com"}}})
srv := New()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"group/g","stream":true,"input":[{"type":"compaction","encrypted_content":"gAAAAB-sealed-by-me"},{"type":"message","role":"user","content":[{"type":"input_text","text":"go on"}]}]}`))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
srv.Handler().ServeHTTP(rec, req)
code, body := rec.Code, rec.Body.String()
tried, _ := b.seen()
if code != 200 || tried != "acct-1" {
t.Fatalf("%d tried %q: %s", code, tried, body)
}
if !strings.Contains(body, "pong") {
t.Errorf("the writer's answer: %s", body)
}
if strings.Contains(tried, "acct-2") {
t.Errorf("the spare, whose list has the model, was asked: %q", tried)
}
// tried, its row leaves the routing page's left: not both attempted
// and unlisted, skipped
for _, w := range lastRoute(srv).Left {
if w.Who == "me@example.com" {
t.Errorf("the writer, tried, still left out: %+v", w)
}
}
}
// #2582, #2642: Codex compacting one of its own models through magpie's
// Codex accounts compacts natively only with the codex provider's native
// compaction on. Off (the default), the trigger never reaches the ChatGPT
// backend: magpie's summary comes back, which any account reads, and no
// account is recorded as the conversation's only reader. Before, the
// trigger was relayed whatever the setting and the seal bound the
// conversation to the account that answered, so switching to another
// account refused it.
func TestCodexOwnModelCompactionHonoursTheToggle(t *testing.T) {
codexSignedIn(t, "spare@example.com")
var mu sync.Mutex
var asked []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
asked = append(asked, r.Header.Get("chatgpt-account-id")+" "+string(b))
mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
if strings.Contains(string(b), "compaction_trigger") {
io.WriteString(w, nativeSealedReply("gAAAAB-sealed-by-chatgpt"))
return
}
io.WriteString(w, sse(
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"SUMMARY"}]}}`,
`data: {"type":"response.completed","response":{"id":"resp_s","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}`))
}))
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
sealed := func(enc string) (checkpointWriter, bool) {
return checkpointOf([]byte(`{"input":[{"type":"compaction","encrypted_content":"` + enc + `"}]}`))
}
code, body := nativeAsk(t, "gpt-5.5", compactTurn)
if code != 200 || !strings.Contains(body, magpieCompaction) || strings.Contains(body, "gAAAAB-sealed-by-chatgpt") {
t.Fatalf("off: %d %s", code, body)
}
mu.Lock()
for _, a := range asked {
if strings.Contains(a, "compaction_trigger") {
t.Errorf("off, the trigger reached the ChatGPT backend: %s", a)
}
}
if len(asked) == 0 {
t.Error("off, no account was asked for the summary")
}
asked = nil
mu.Unlock()
if cp, ok := sealed("gAAAAB-sealed-by-chatgpt"); ok {
t.Errorf("off, a writer was recorded: %+v", cp)
}
nativeOn(t, "codex")
code, body = nativeAsk(t, "gpt-5.5", compactTurn)
if code != 200 || !strings.Contains(body, `"encrypted_content":"gAAAAB-sealed-by-chatgpt"`) || strings.Contains(body, magpieCompaction) {
t.Fatalf("on: %d %s", code, body)
}
mu.Lock()
if len(asked) != 1 || !strings.Contains(asked[0], `{"type":"compaction_trigger"}`) {
t.Errorf("on, the backend was asked %q", asked)
}
mu.Unlock()
if cp, ok := sealed("gAAAAB-sealed-by-chatgpt"); !ok || cp.Who != "codex@me@example.com" {
t.Errorf("on, the writer recorded is %+v %v", cp, ok)
}
}
// #2642: a conversation whose native compaction's account can't be asked
// is told why, as magpie's settings say, and what lets it go on — not
// "switched off, removed, or no longer serves" of an account that is on.
// No other account is asked.
func TestNativeCompactionWriterGoneSaysWhy(t *testing.T) {
ask := func(t *testing.T, enc string) (int, string) {
t.Helper()
return codexPost(t, `{"model":"gpt-5.5","stream":true,"input":[{"type":"compaction","encrypted_content":"`+enc+`"},{"type":"message","role":"user","content":[{"type":"input_text","text":"go on"}]}]}`)
}
account := func(user string) candidate {
return candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{User: user}}, model: "gpt-5.5"}
}
for _, c := range []struct {
name, writer string
set func(t *testing.T)
want, not []string
}{
{"spare switched off", "spare@example.com",
func(t *testing.T) {
if err := provider.SetLoginOn("codex", "spare@example.com", false); err != nil {
t.Fatal(err)
}
},
[]string{"switched off in magpie", "switch spare@example.com on again", "the others can stay on beside it"},
[]string{"no longer signed in", "paused"}},
{"own paused", "me@example.com",
func(t *testing.T) {
if err := provider.SetLoginOn("codex", "me@example.com", false); err != nil {
t.Fatal(err)
}
},
[]string{"it is paused", "turn me@example.com on again"},
[]string{"no longer signed in", "switched off in magpie"}},
{"kept from the model", "me@example.com",
func(t *testing.T) {
if err := provider.SetAccountModels("codex", "me@example.com", []string{"gpt-4.1"}); err != nil {
t.Fatal(err)
}
},
[]string{"set not to serve gpt-5.5 (Names & levels)", "let me@example.com serve gpt-5.5 again"},
[]string{"no longer signed in", "switched off in magpie", "paused"}},
{"signed out", "gone@example.com", func(t *testing.T) {},
[]string{"gone@example.com is no longer signed in to magpie", "sign in to gone@example.com again"},
[]string{"switched off in magpie", "paused"}},
} {
t.Run(c.name, func(t *testing.T) {
codexSignedIn(t, "spare@example.com")
b := newResetBackend(t)
c.set(t)
enc := "gAAAAB-sealed-" + strings.ReplaceAll(c.name, " ", "-")
wroteCheckpoint(enc, account(c.writer))
code, body := ask(t, enc)
if tried, _ := b.seen(); code != 400 || tried != "" {
t.Fatalf("%d tried %q: %s", code, tried, body)
}
for _, want := range append(c.want, "compacted natively by codex@"+c.writer, "sealed (encrypted) to that account", "start a new conversation", "Native compaction is off for codex now") {
if !strings.Contains(body, want) {
t.Errorf("no %q in %s", want, body)
}
}
for _, not := range append(c.not, "switched off, removed, or no longer serves", "Switch codex@") {
if strings.Contains(body, not) {
t.Errorf("%q in %s", not, body)
}
}
})
}
}
+4 -1
View File
@@ -67,7 +67,9 @@ func restingNow(t *testing.T) []string {
// Codex's own model, three ChatGPT accounts on, the backend answering 502
// "response protection is unavailable" for that history. It is the
// request, not an account: asked once, not on every account and then the
// last again, and no account rests for it.
// last again, and no account rests for it. The compaction goes to the
// backend as it came only with native compaction on (#2582); off, magpie
// summarises it, as TestProtectionRefusedCompactionAsText's model is.
func TestProtectionRefusalAskedOnceNobodyRests(t *testing.T) {
for _, said := range []string{
`{"error":{"message":"response protection is unavailable","type":"server_error"}}`,
@@ -75,6 +77,7 @@ func TestProtectionRefusalAskedOnceNobodyRests(t *testing.T) {
} {
t.Run(said, func(t *testing.T) {
codexSignedIn(t, "two@example.com", "three@example.com")
nativeOn(t, "codex")
tried := protectionUp(t, said)
code, body := codexPost(t, strings.Replace(protectedCompaction, "%q", `"gpt-5.5"`, 1))
if code != http.StatusBadGateway || !strings.Contains(body, "response protection is unavailable") {
+7
View File
@@ -381,6 +381,13 @@ type planned struct {
// cap set on them, for a conversation that stays strictly on one to
// go on there (provider.AffinityStrict, #1797)
capped []candidate
// unlisted: the accounts left out (in left) as their own list lacks
// the model, their rows beside them in unlistedW, kept for the
// checkpoint narrowing: the one that sealed a conversation's compaction
// is tried for it as the last resort an account whose list lacks the
// model is, though no other can read it
unlisted []candidate
unlistedW []Weighed
}
func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from provider.Protocol) Weighed {