Skip to content

fix(openai): unify server-side compaction gates and harden compaction recovery - #123397

Merged
steipete merged 10 commits into
mainfrom
steipete/server-side-compaction-review-8cf8ab
Aug 14, 2026
Merged

steipete merged 10 commits into
mainfrom
steipete/server-side-compaction-review-8cf8ab

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Two disagreeing definitions of "OpenAI server-side compaction is enabled" existed. The host gate (resolveResponsesServerCompactionThreshold in src/auto-reply/reply/memory-flush.ts) decided from the responsesServerCompaction param alone (default-on for provider openai) and raised/delayed the client-side preflight compaction threshold when responsesCompactThreshold was set. The transport gate (packages/ai/src/transports/openai-responses-payload-policy.ts) additionally requires a store-capable native route, which excludes openai-chatgpt-responses (OAuth), non-native base URLs, Azure cognitiveservices hosts, and supportsStore: false models.

Failure mode: a ChatGPT-OAuth session with responsesCompactThreshold configured delayed client compaction while the transport never injected context_management — neither side compacted until hard overflow. Separately, the transport auto-injected a default compact_threshold (70% of context window) the host never learned, so client and server compaction raced blindly.

A compaction review sweep also surfaced bounded adjacent bugs fixed here (see below).

Why This Change Was Made

  • One shared resolver now owns enablement + effective threshold: resolveOpenAIResponsesServerCompactionPlan (payload policy). The transport policy consumes it internally; the host resolver consumes it with catalog-resolved model facts. A 10-route parity table test asserts host-gate enablement === transport-gate context_management injection (OpenAI default/native, OAuth, Azure both host families, casing, supportsStore:false, proxy, explicit on/off).
  • The host now learns the effective default threshold (70% of context window), so client preflight compaction defers to server compaction instead of racing it.
  • Canonical OPENAI_RESPONSES_APIS alias set (now including openclaw-azure-openai-responses-transport) is exported once from openai-responses-contracts.ts and consumed by the payload policy, transcript redaction, and the transport alias map — previously the proxy/TLS transport rewrite silently disabled store forcing and context_management for Azure routes.
  • Azure endpoint classification now recognizes cognitiveservices.azure.com, services.ai.azure.com, and api.cognitive.microsoft.com hosts as Azure OpenAI (matching the Azure provider's supported hosts).
  • Bounded compaction bug fixes, each with a pre-fix-failing regression test:
    • Anthropic direct-API overflow wording (input length and `max_tokens` exceed context limit: N + M > K) is now classified as assistant-error overflow (compact-and-retry instead of failover), unanchored so wrapped HTTP 400: {json} transport errors match; the observed-token extractor parses the colon-sum form.
    • shouldCompact rejects non-positive/non-finite context windows (previously contextWindow: 0 compacted after every turn).
    • Image token estimates unified at 2,000 tokens/image between the cut-point engine and the preflight budget gate (previously 1,200 vs 2,000 caused immediate re-triggering on image-heavy sessions).
    • Orphaned function_call_output rejection (call_id inside the encrypted compaction blob) now routes to the compaction-stripped full-history retry instead of failing the turn.
    • Compaction capture skipped for missing baseUrlHash now logs at debug level.
    • Removed the partialSummary non-null assertion; clarified the diagnostic-only prompt-pressure precheck comment.

Known limitation (no regression): the host resolver reads config/catalog-resolved routes; an OAuth auth-profile that later selects the ChatGPT backend at runtime is not observable pre-turn. That case previously mis-raised the threshold; now it behaves the same as before at worst.

Deliberately out of scope (companion work in flight): WebSocket-transport compaction fallback, Anthropic server-side compaction (compact_20260112) adoption. Named follow-ups: persisting the compaction-suppression tombstone when the retried turn fails; replayIndex content-identity guard (blocked on the closed worker-admission schema); Codex tokensAfter refresh after native compaction.

User Impact

  • ChatGPT-OAuth, Azure Cognitive Services, and supportsStore: false sessions no longer get their client-side compaction delayed by a server threshold that never applies.
  • Azure Responses sessions behind request.proxy/request.tls regain store forcing and server-side compaction.
  • Claude direct-API sessions hitting the max_tokens context-limit error now auto-compact instead of failing over or surfacing the error.
  • Image-heavy sessions stop thrash-compacting.

Evidence

  • Parity table test (10 routes) in src/agents/openai-responses-payload-policy.test.ts; host-gate tests in src/auto-reply/reply/memory-flush.test.ts.
  • Focused suites green: payload policy, prompt observer (incl. new orphaned-output end-to-end recovery test), compaction replay, overflow classification, agent-core compaction, preemptive compaction, memory-flush (350+ tests across touched files). pnpm tsgo green.
  • Live proof 1 (raw API): POST api.openai.com/v1/responses with store: true + context_management: [{type:"compaction", compact_threshold: 1000}] returned HTTP 200 with encrypted compaction output items (2,380 encrypted bytes).
  • Live proof 2 (full pipeline): OPENCLAW_LIVE_TEST=1 OPENCLAW_LIVE_OPENAI_COMPACTION=1 pnpm test:live src/agents/sessions/agent-session.openai-compaction.live.test.ts — passed; server compactions observed at turns 3 and 5 with prompt tokens dropping 56,854 → 38,346 after compaction.
  • Codex remote-compaction contracts cross-checked directly in sibling ../codex source: codex-rs/model-provider/src/provider.rs:30 (V1 /v1/responses/compact, V2 compaction_trigger), codex-rs/core/src/tasks/compact.rs:41 (provider capability gate), codex-rs/core/src/compact_remote_v2.rs:396 (exactly-one compaction output contract).

@clawsweeper

clawsweeper Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@steipete
steipete marked this pull request as ready for review August 14, 2026 00:48
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Aug 14, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 14, 2026
@clawsweeper

clawsweeper Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 13, 2026, 11:17 PM ET / August 14, 2026, 03:17 UTC.

ClawSweeper review

What this changes

This PR centralizes eligibility and threshold calculation for OpenAI Responses server-side compaction, while adding recovery fixes and regression tests for related compaction failures.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open for maintainer handling: the item carries the protected maintainer label, and the read-only inspection environment failed before any local source, history, or policy command could run.

Priority: P2
Reviewed head: e2379f792a5ba2cc47c3b17d559beea510d2331a
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The supplied patch and validation claims are substantive, but infrastructure failure prevented the source and exact-head review needed to rate it more highly.
Proof confidence 🌊 off-meta tidepool Not applicable: The repository state identifies this as a member-authored maintainer PR; its body also reports live raw-API and full-pipeline evidence, but those claims could not be inspected locally.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The repository state identifies this as a member-authored maintainer PR; its body also reports live raw-API and full-pipeline evidence, but those claims could not be inspected locally.
Evidence reviewed 4 items Protected-label handling: The supplied PR context includes the maintainer label, which requires explicit maintainer handling rather than automated closure.
Submitted implementation scope: The supplied head patch places the shared policy in the Responses transport and consumes it from the memory-flush preflight path.
Inspection infrastructure failure: The required local source, history, and full on-disk policy review could not start because the sandbox rejected the read-only command before execution: bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted.
Findings None None.
Security None None.

How this fits together

The agent runner decides when to compact local conversation history before a provider call. OpenAI Responses routes can request provider-side compaction instead, so preflight and transport payload construction need the same route and threshold decision.

flowchart LR
  A[Agent session] --> B[Local preflight gate]
  B --> C[Shared compaction plan]
  C --> D[Responses payload policy]
  D --> E[OpenAI or Azure route]
  E --> F[Compacted response]
  F --> G[Replay and recovery]
Loading

Decision needed

Question Recommendation
Does the verified upgrade behavior for existing responsesServerCompaction and responsesCompactThreshold configurations match the compatibility contract maintainers want to ship? Validate route matrix then merge: Run exact-head fresh-install and upgrade-route checks for all affected route classes, then merge if the observed behavior matches the documented contract.

Why: The PR intentionally changes when existing routes defer local compaction, and protected maintainer handling requires an explicit merge decision after route validation.

Before merge

  • Resolve merge risk (P1) - The shared resolver changes how existing OpenAI Responses route configurations defer local compaction, so exact-head upgrade-route behavior remains compatibility-sensitive.
  • Resolve merge risk (P1) - The sandbox failure prevented the required source, caller, history, scoped-policy, and current-main review; no merge verdict can be evidence-backed until that is retried.
Agent review details

Security

None.

PR surface

Source +39, Tests +358, Docs +6, Config +8, Other +7. Total +418 across 34 files.

View PR surface stats
Area Files Added Removed Net
Source 19 143 104 +39
Tests 9 361 3 +358
Docs 2 14 8 +6
Config 2 8 0 +8
Generated 0 0 0 0
Other 2 7 0 +7
Total 34 533 115 +418

Review metrics

Metric Value Why it matters
Production versus test LOC delta production +158/-104, tests +361/-3, docs +14/-8 The supplied file-level patch stats show substantial test coverage alongside a net production increase for provider-compaction behavior.

Stored data model

Persistent data-model change detected: unknown-data-model-change: src/auto-reply/reply/memory-flush.test.ts, unknown-data-model-change: src/auto-reply/reply/memory-flush.ts, vector/embedding metadata: packages/ai/src/transports/openai-responses-compaction-replay.ts, vector/embedding metadata: src/auto-reply/reply/memory-flush.test.ts, vector/embedding metadata: src/auto-reply/reply/memory-flush.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Prove existing route behavior (recommended)
    Validate fresh and upgraded configurations for direct OpenAI, Azure, OAuth, custom-proxy, and supportsStore: false routes before merge.
  2. Pause for compatibility direction
    Hold the PR if maintainers do not want existing non-store-capable routes to resume local preflight compaction.

Technical review

Best possible solution:

Validate exact-head fresh and upgraded configurations across direct OpenAI, Azure, ChatGPT OAuth, custom-proxy, and supportsStore: false routes, then make the merge decision on the verified compatibility contract.

Do we have a high-confidence way to reproduce the issue?

Unclear: the PR describes focused live and test reproductions, but the review environment could not inspect the implementation or execute the supplied paths.

Is this the best way to solve the issue?

Unclear: centralizing the two gates is plausible, but the required owner-boundary, caller, sibling-route, and upgrade review could not be completed locally.

AGENTS.md: unclear because the file could not be read completely.

Codex review notes: model internal, reasoning high; reviewed against 502bdb2bb789.

Labels

Label justifications:

  • P2: This is a bounded reliability repair affecting existing provider compaction behavior.
  • merge-risk: 🚨 compatibility: Existing Responses configurations can change from deferred local compaction to local compaction based on resolved route capability.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The repository state identifies this as a member-authored maintainer PR; its body also reports live raw-API and full-pipeline evidence, but those claims could not be inspected locally.

Evidence

What I checked:

  • Protected-label handling: The supplied PR context includes the maintainer label, which requires explicit maintainer handling rather than automated closure. (e2379f792a5b)
  • Submitted implementation scope: The supplied head patch places the shared policy in the Responses transport and consumes it from the memory-flush preflight path. (packages/ai/src/transports/openai-responses-payload-policy.ts, e2379f792a5b)
  • Inspection infrastructure failure: The required local source, history, and full on-disk policy review could not start because the sandbox rejected the read-only command before execution: bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted.
  • Current-main status cannot be established: The supplied context identifies current main as 502bdb2, but the failed local inspection prevents verifying whether it already contains this PR's central repair. (502bdb2bb789)

Likely related people:

  • steipete: All ten supplied commits on the repair branch are attributed to steipete; current-main ownership could not be established because local git history was unavailable. (role: author of the current repair series; confidence: low; commits: 4b9b88119476, e2379f792a5b; files: packages/ai/src/transports/openai-responses-payload-policy.ts, src/auto-reply/reply/memory-flush.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Retry the read-only source, history, scoped-policy, and exact-head route review once the sandbox permits commands.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-14T01:22:16.706Z sha 51cdbfc :: needs maintainer review before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Aug 14, 2026
@steipete
steipete merged commit 575467a into main Aug 14, 2026
263 of 265 checks passed
@steipete
steipete deleted the steipete/server-side-compaction-review-8cf8ab branch August 14, 2026 03:45
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 14, 2026
… recovery (openclaw#123397)

* fix(openai): unify server compaction policy

* fix(openai): preserve managed responses aliases

* fix(compaction): harden bounded recovery

* refactor(compaction): simplify orphan output classifier

* fix(compaction): unanchor overflow classifiers and route image constant through runtime facade

* test(openai): use provider input config in compaction parity

* test(openai): model default compaction route accurately

* fix(openai): isolate responses payload policy imports

* fix(ai): remove unused responses api re-export

* fix(plugins): resolve responses policy source alias
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant