Skip to main content

Fix OpenClaw context_length_exceeded and Failed Compaction

For a large OpenClaw session, save the task state and try supported manual compaction. If the summary request also exceeds its limit, resume in a fresh session from a short record of completed work. Fresh-session failures require checking fixed overhead and the local model's loaded context.

LaoZhang AI TeamPublishedUpdated 15 min read
On this page
OpenClaw context includes system instructions, tools, workspace files, history and tool output

To recover from OpenClaw's context_length_exceeded, first preserve what the agent has already done. If conversation history is the main source of pressure, run /compact in a runtime that supports it, then check that the next small request succeeds. If the session is too large to compact, save a short task record outside the failing conversation and use /new to continue from that record. If a fresh session still overflows, inspect the fixed prompt, tool schemas, workspace injection, and the actual context loaded by your model server.

The rejected request includes much more than your latest message. A compaction request has its own input and output budget, so asking for a summary can fail too. Increasing OpenClaw's model metadata or selecting a larger summarization model cannot expand the foreground model's real window. The recovery behavior described below follows the built-in OpenClaw compaction documentation; native backends and custom context engines can differ.

Save completed work before retrying or starting a new session

An overflow error does not mean earlier tool actions were undone. A file may already have changed, a job may have started, or an external action may have completed before the next model request failed. Inspect the actual result before repeating any of those actions.

Keep a short recovery note in a file or other record you control. Capture:

  • The current goal and the exact request that has not yet been answered.
  • Completed changes, affected file paths, and the checks actually run.
  • Decisions and identifiers needed to continue, such as a job ID or document URL.
  • Actions with external effects, their observed results, and anything whose completion is uncertain.
  • The next small step and any constraint that still applies.

For example, this fictional task record is sufficient to restart a narrow coding step without pasting the entire conversation:

Goal: repair the CSV import error in this workspace.
Completed: changed src/import.ts; preserved the original CSV fixture.
Verified: the unit test for blank rows passed. No full integration test yet.
Pending request: check the date-column case, then report the remaining failure.
External actions: none. Do not commit, push, or deploy.
Next step: read the date parsing function and the small date fixture only.

If the current agent can still reply, ask it to write that record and inspect the saved file. If every model call fails, collect it yourself from the visible transcript, files, and recorded tool results. Do not make saving your work depend on another oversized model request.

OpenClaw's built-in compactor retains the full conversation history on disk while changing what the next model call sees. That history is useful for explicit retrieval; it does not mean a summary retains every detail. In the current built-in implementation, active history uses SQLite, so deleting an old JSONL file or editing sessions.json is not a reliable recovery procedure. Compaction behavior explains the retained history and current transcript behavior.

Identify which request exceeded which limit

Run these commands separately in the affected chat:

/status
/context list
/context detail

/context list identifies injected files and rough sizes. /context detail adds tool-schema and system-prompt contributions, helping distinguish a large fixed prompt from compactable history. /context map can provide a visual breakdown after the session has a cached run report; before then, use the list or detail commands. The context guide documents these views and their limits.

On the Gateway host, inspect the relevant attempt in the logs:

bash
openclaw logs --follow

Record the first useful provider error, the actual model/provider attempt, whether it occurred during normal inference or summarization, and any requested-token and maximum-token counts. Keep request IDs when available, but remove credentials and private task content before sharing diagnostics.

EvidenceWhat it establishesNext action
A normal model request reports input above its accepted maximumThat attempt exceeded the selected route's usable budgetReduce history or the new input; verify the actual model route
/compact reports a prompt or session too large to summarizeThe recovery request itself did not fitPreserve the task record; change the summary path or start a fresh session
A fresh session fails before a substantial file readRemoving old conversation was insufficientInspect fixed context and loaded backend capacity
The failure follows a different provider/model attemptThe rejected attempt may have a different budget from the selected primaryRead the per-attempt chain before changing the primary's context settings
/status looks low, but the provider rejects the requestThe displayed count does not explain the actual rejectionCompare the current request, model, effective cap, and cached measurement

The Control UI's last-run prompt budget is an estimate tied to the selected model and effective context cap. A model change can make an older reading stale. A displayed contextTokens value is a runtime estimate, not proof that the provider accepted the next request and not a billing total. The technical reference distinguishes model capacity from session counters.

Context contributors and output reserve vary with the actual model and request

The illustration shows why history growth matters. Use your actual context report and the current configuration reference for limits and settings; the figures in an illustration are not measurements of your session.

Compact a long session and verify the next turn

For the built-in OpenClaw runtime, manual compaction is the least disruptive option when old history is the main problem and the summarization request can still fit:

/compact Preserve the pending request, completed changes, exact file paths, and unresolved checks.
/status

The focus text guides the built-in summarizer; it is not a guarantee of lossless preservation. Recent turns are kept verbatim, and tool calls stay paired with their results when OpenClaw chooses the split point. Older material is summarized. The summary persists in the session transcript. Manual compaction describes the supported command and its runtime differences.

For native Codex sessions, check that backend's support: when manual compaction is available, use bare /compact, because focus text is not passed through. Native Codex sessions using Sign in with ChatGPT support automatic compaction but cannot run manual /compact. A custom context engine also owns its own compaction behavior.

Verify recovery with a small, read-only next step. For the fictional CSV task, ask the agent to read only the date parsing function and identify the pending test. Check that it sees the correct goal, reads the intended file range, and produces a reply without another context rejection. A higher compaction count or a “complete” log establishes that compaction occurred; successful continuation establishes more than a lower estimated meter alone.

If the same failure recurs with the same request, stop repeating /compact unchanged. Determine whether the retained tail, fixed prompt, new input, or summarizer budget still prevents the request from fitting.

“Session too large to compact”: recover when the summary also fails

Compaction is another model request. It needs room for the selected history, summary instructions, preserved recent material, and the generated summary. A giant file result or tightly paired tool block can exceed that budget even when the ordinary conversation seemed manageable.

A historical OpenClaw issue, #20760, illustrates this distinction. The reporter, using version 2026.2.17 on Windows with WSL, described manual compaction requesting 202,350 tokens against a 200,000-token limit after a large file read. The issue is closed as not planned; its status does not establish a current fix or a current installation's cause. It is a reported example, not a reproduction performed for this guide.

Choose the recovery according to the failing request:

  1. If summarization is failing because its model or endpoint cannot accept the input, use a summarization model with a verified adequate budget, or reduce the material that must be carried forward. agents.defaults.compaction.model selects a compaction-only model in the built-in runtime. It needs its own available route and credentials; it does not enlarge the foreground window. An explicit override is exact and does not inherit the session's fallback chain. See the compaction model setting.
  2. If you cannot produce a usable summary, preserve the task record and start a new session. In chat, send /new, then send that short record and one narrow next request. The session documentation lists both /new and /reset as manual new-session commands. Do not treat /reset as a command to delete durable memory.
  3. In the new session, verify the actual files or external results before asking the agent to continue. Tell it which actions are complete and which are uncertain. Do not paste the huge transcript or repeat the large file read that caused the original failure.

This fresh session still loads system instructions, tools, and applicable workspace context. If even the short recovery note fails, leave the history branch and inspect fixed overhead or backend capacity. Creating more blank sessions will not remove those contributors.

Success means the new session understands the pending task, confirms existing work, and completes the next bounded step. If that step would repeat an external action whose result is unknown, stop and inspect that result first.

“Auto-compaction failed”: distinguish overflow, timeout, and summary rejection

Find the summarizer's error before tuning its settings. A context rejection, a silent summary timeout, and a rejected safeguard summary require different responses.

Compaction failureWhat to doWhat to verify
Summary input exceeds its limitFollow the too-large-to-compact recovery aboveA smaller summary input or adequate summary route, followed by a successful small turn
No progress while summarizingInspect streaming/progress logs and the compaction timeout settingWhether the run is still active, timed out, or cancelled
Safeguard summary fails validationPreserve the original history; check the failed summary and required pending detailsA usable summary rather than merely suppressing the quality check
Required compaction cannot recoverSave work and move to a short fresh-session recordExisting actions were inspected and the pending request continues once

In the current built-in runtime, agents.defaults.compaction.timeoutSeconds defaults to 180 seconds without progress. Streamed output refreshes that window; it is not always a three-minute wall-clock limit. The complete compaction operation is limited to ten such windows, or 30 minutes with the default setting. Increasing this setting only helps a summary that needs time; it cannot make an oversized input fit. These semantics are documented in the current compaction configuration.

There is a specific automatic-timeout exception. If an automatic summary deadline expires, or its provider returns HTTP 408 or 504 while the turn is still active, the built-in runtime can continue without a newly generated summary. It retains the pending request, recent messages and complete tool pairs, and carries forward the previous summary. Older facts that had not already been summarized can leave the active context. The complete transcript remains available for explicit retrieval. Logs identify this path with reason=timeout summary=deterministic. The automatic-compaction documentation describes this behavior.

That exception does not promise the same recovery for manual /compact, other summarizer errors, or a stopped run. Safeguard quality failure normally leaves the original history intact rather than storing a known-invalid summary. After degraded continuation, verify any older fact needed for the next action from its source file or transcript; do not assume the model still knows it.

For provider overflow after settled tool results, the built-in runtime can continue from recorded results without replaying completed actions. Pending tools, approvals, and other runtimes retain their own handling. Stopping a run stops further recovery, but cancellation does not undo a compaction or external action that already completed. This is why preserving and inspecting work comes before a retry.

Local model context is too small, even on a fresh session

Check the model instance that is actually serving OpenClaw, not just the model card or a contextWindow number in configuration. With LM Studio, a loaded instance's context takes precedence over the larger advertised maximum. OpenClaw's preload path prepares an instance for the selected budget; disabling preload hands loading to LM Studio's JIT and lifecycle settings. The LM Studio provider guide documents both paths.

For a local-context mismatch:

  1. Identify the exact model and loaded instance behind the failed request. Compare the server's loaded context with OpenClaw's configured budget.
  2. Either load an instance with enough context for the assembled agent request, or lower the requested budget and reduce the prompt to fit the instance you can run. If the larger context cannot load on your hardware, select a suitable model or split the task.
  3. Keep OpenClaw's metadata consistent with the backend's actual capacity. Changing metadata alone is not a reload and cannot create server capacity.
  4. In the affected chat, verify a short reply and a harmless read-only tool task. Then retry one small part of the original workload.

A tiny text-only prompt passing through the server does not prove that the same instance can accept OpenClaw's tools and workspace instructions. If you need to reconnect the server, choose the exact model, or check strict versus default selection, use the OpenClaw LLM setup guide.

Also inspect the actual fallback attempt. The current failover policy can use configured chains for defaults and other eligible selection sources, while an explicit user-selected session model is strict. A successful fallback is turn-local; it does not change the session's selected model for the next turn. If logs show a primary rate limit followed by an overflow on a smaller fallback, those are two distinct errors. The smaller-window explanation is an inference to check against the recorded attempts, not something a 429 alone proves. Model failover describes the attempt chain.

Reduce the contributor that keeps filling the window

Use /context detail to decide what to change. History, fixed instructions, and tool output respond to different controls.

Dominant contributorUseful changeBoundary
Long conversation historyCompact or restart with the task recordSummaries are lossy; retain exact material needed later outside the model window
Large file reads or command outputRequest exact ranges, relevant matches, or a concise resultPreserve the full output as an artifact when needed; avoid pasting it all back into chat
Large injected workspace filesMove task-specific detail to files read on demand; remove obsolete duplicationKeep required instructions and safety constraints available
Large tool schemasLimit the tools enabled for this task or choose sufficient context capacityDo not remove a capability the task needs merely to lower a meter
Retrieved materialNarrow the retrieval question and inspect the snippets being loadedReduce irrelevant retrieval rather than deleting durable memory
Local loaded-context mismatchAlign the loaded instance and configured budgetMetadata cannot exceed the server's real capacity

The documented bootstrap limits, bootstrapMaxChars and bootstrapTotalMaxChars, are character limits, not token allowances. Their default values are 20,000 characters per file and 60,000 in total. Reducing them can truncate instructions rather than safely summarize them. Inspect raw versus injected sizes in the context report before changing these limits.

Pruning can help when old tool results dominate, but it is not automatically enabled for every provider. The bundled Anthropic plugin can seed cache-TTL pruning; other providers have it off unless configured. Eligible direct Anthropic API-key requests use server-side clearing, while eligible client routes use TTL and context checks. Client-side projections are recorded so they can survive a Gateway restart; original tool results remain in the transcript. Normal conversation text is outside this tool-result pruning mechanism. See session pruning.

Therefore, pruning may reduce the next prompt without reducing stored history, and restarting the Gateway may restore the same reduced projection. Turning pruning off stops new rounds; it does not restore every existing projection to the next prompt. Use compaction or a fresh session according to the task, rather than deleting history to force a smaller request.

Save completed work, compact when supported, or continue a fresh session from a short record

Follow the request evidence and recovery steps in the text. A meter percentage alone does not establish a current bug or justify ignoring a provider rejection.

Set compaction budgets without copying an old reserve recipe

The current built-in embedded runtime uses a 20,000-token reserve, capped at one quarter of the active model window. keepRecentTokens defaults to 20,000 and defines the manual compaction cut point. Automatic compaction can retain less recent history because it also accounts for the fixed prompt, tool schemas, pending input, and output reserve. A larger kept tail can make the replacement harder to fit. The compaction reference explains these budgets.

For the documentation's 32,768-token window example:

Reserve:                 min(20,000, 32,768 / 4) = 8,192
Compaction threshold:    32,768 - 8,192           = 24,576
Early memory flush:      24,576 - 4,000           = 20,576

These are the documented example's arithmetic, not measurements of your session. An applicable server threshold can move blocking compaction later. The 4,000-token soft margin belongs to agents.defaults.compaction.memoryFlush.softThresholdTokens: it is the gap before compaction at which durable-memory flushing can start. It is not memorySearch.softThresholdTokens, a retrieval output limit, or extra model capacity. Memory-flush housekeeping gives the full example.

As a separate hypothetical request, suppose disjoint system instructions, tool schemas, workspace injection, and pending input total 14,000 tokens, with 8,000 tokens of history. The 22,000-token prompt fits below that 24,576 maintenance threshold. Adding a 4,000-token tool result brings it to 26,000: above the threshold, but still below the 32,768 window. Adding a 12,000-token result instead brings it to 34,000, above the window by 1,232 tokens even before further overhead. This is why “the last message is short” and “the meter was below 100%” do not settle the next request's size.

Do not paste a fixed reserveTokens or reserveTokensFloor recipe from an older guide into an unknown installation. The current reference describes a built-in capped reserve; older field support must be checked against your installed schema. Before editing the identified compaction field, inspect the active configuration and validate it:

bash
openclaw config file
openclaw config get agents.defaults.compaction
openclaw config schema
openclaw config validate

These are documented CLI checks for the operator to run on the Gateway host. This guide has not executed them against your installation. Preserve other settings, apply only the change the diagnosis supports, validate again, and follow the CLI's actual reload or restart guidance. Schema validation and a reload hint do not establish a successful model request. The config CLI reference describes their scope.

Disabling memoryFlush skips that housekeeping step; it does not disable compaction. Setting compaction.enabled to false suppresses proactive threshold behavior in the built-in runtime, while manual and overflow-recovery paths remain available. Neither is a general fix for an oversized request. The optional maxActiveTranscriptBytes guard triggers semantic compaction from transcript size and is disabled when unset; it is separate from the memory-flush byte trigger. Change a control only when it matches the contributor or failure you observed.

Questions that matter after recovery

Does /reset clear OpenClaw's persistent memory?

Do not rely on it for that purpose. OpenClaw documents /new and /reset as manual new-session commands. Durable memory and the active model context are separate. For context recovery, keep the saved task record, start the new session, and verify what it actually loads. The session guide does not establish that resetting a conversation deletes durable memory.

Can a bigger compaction model fix a smaller foreground window?

It can help summarize input that the original summarizer cannot handle, provided that route supports the request. The final foreground request must still fit its own window. Fixed instructions, retained history, and the pending request continue to count. Manual and automatic compaction have different budgeting behavior.

Does lower context usage mean the API bill dropped by the same amount?

No. A context estimate describes the active request; charges depend on the route's input, output, caching, and other billing rules. Compaction can itself make model calls. Keep context counters separate from measured usage and provider billing instead of converting a window percentage into claimed savings. Compaction behavior explicitly separates context estimates and billing totals.

What should I collect if a short fresh session still fails?

Collect the OpenClaw version, runtime or context engine, actual provider/model attempt, loaded local context when applicable, context breakdown, and the exact normal-request or summary error. Include a small reproducible input and the observed token limits when available. Exclude secrets and unrelated private content. Stop retrying the unchanged request; the evidence should show whether the remaining problem is fixed overhead, backend capacity, a route limit, or a version-specific failure.

Sources11

External pages this guide links to, in the order they appear. Last updated Oct 5, 2026.

  1. 1.built-in OpenClaw compaction documentationdocs.openclaw.ai/concepts/compaction
  2. 2.Compaction behaviordocs.openclaw.ai/reference/session-management-compaction/compaction
  3. 3.context guidedocs.openclaw.ai/concepts/context
  4. 4.OpenClaw issue, #20760github.com/openclaw/openclaw/issues/20760
  5. 5.session documentationdocs.openclaw.ai/concepts/session
  6. 6.current compaction configurationdocs.openclaw.ai/gateway/config-agents/heartbeat-compaction-and-streaming
  7. 7.The LM Studio provider guidedocs.openclaw.ai/providers/lmstudio
  8. 8.Model failoverdocs.openclaw.ai/concepts/model-failover
  9. 9.session pruningdocs.openclaw.ai/concepts/session-pruning
  10. 10.Memory-flush housekeepingdocs.openclaw.ai/reference/session-management-compaction/housekeeping
  11. 11.The config CLI referencedocs.openclaw.ai/cli/config
More in Troubleshooting
OpenClaw 429 diagnosis separates model-provider requests from ClawHub skill downloads
Troubleshooting

Fix OpenClaw 429 Rate Limit Errors: Wait, Recover, or Use a Fallback

When OpenClaw reports a 429, pause extra requests and identify whether the rejection came from the model provider or ClawHub. Wait for a temporary limit, repair exhausted quota or access, and check whether the current selection permits fallback. Preserve completed work before continuing.

13 min
Conceptual OpenClaw connection map separating Gateway, provider and channel credentials and identifying the host, agent, session and model that failed
Troubleshooting

OpenClaw API Key Errors: Fix Missing Keys, 401, 429, and Gateway Auth

For an OpenClaw API key error, identify the connection that rejected the request before changing credentials. A missing provider key, a Gateway token mismatch, and a provider rate limit need different repairs. Verify recovery in the same agent, session, and model that failed.

19 min
OpenClaw authentication overview separates rejected bearer tokens, missing headers, and agent credentials
Troubleshooting

Fix OpenClaw 401 Errors: Invalid Bearer Token and Missing Auth Header

For an OpenClaw 401, first identify who rejected the request. An invalid provider token, a missing outgoing auth header, and a Gateway or device-token mismatch require different fixes. Check the failing agent and session before replacing credentials.

12 min
Identify the rejected beta header and its selected provider while preserving required features
Troubleshooting

Fix OpenClaw Invalid Beta Flag: Find the Rejected Header and Repair Its Route

Repair an OpenClaw invalid beta flag error by identifying which feature header the selected provider rejected and where it was added. Remove an unsupported optional flag, or repair the required feature's route, then confirm both configuration loading and a completed request.

11 min
OpenClaw Anthropic API Key Error Fix Guide showing error types and solutions
Troubleshooting

Fix OpenClaw Anthropic API Key Error: 401, Missing Auth, OAuth, and Cooldown

OpenClaw Anthropic API key errors need an owner-first read: prove whether Anthropic auth is missing, the key is rejected, OAuth cannot refresh, an env var overrides config, the selected model is unavailable, or OpenClaw is only showing a provider cooldown after an earlier failure.

18 min