Skip to content

perf(agents): amortize history-limit eviction with hysteresis - #115281

Merged
steipete merged 1 commit into
mainfrom
steipete/history-limit-hysteresis-115273
Jul 28, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/history-limit-hysteresis-115273

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Channel historyLimit/dmHistoryLimit sessions get a per-turn sliding window: once past the limit, every new user turn shifts the outbound prompt's start by one message, so the provider prompt cache never hits again for the life of the session (~0% prefix-cache hits, paid every turn).

Closes #115273.

Why This Change Was Made

limitHistoryTurns (src/agents/embedded-agent-runner/history.ts) now applies hysteresis instead of exact-limit trimming: the window may grow to ceil(limit × 1.5), and the keep count is derived with mod arithmetic so the absolute window start stays byte-identical for a full eviction batch of consecutive turns, then cuts back toward the limit in one step — amortizing one cache break over many turns, the same way compaction amortizes its boundary break. The function stays a pure, deterministic function of the message list and limit; no state, no timestamps.

User Impact

Long channel sessions with a history limit regain provider prompt-cache reuse (lower cost and latency). Named tradeoff: the model temporarily sees up to 50% more turns than the configured limit; it never sees fewer. The compaction-execution caller sees the same bounded growth (slightly larger summarization input), which is harmless.

Evidence

  • node scripts/run-vitest.mjs src/agents/embedded-agent-runner.limithistoryturns.test.ts — 16 tests passed, covering below-limit passthrough, stable window start between cuts, single-step cutback on crossing 1.5×, repeated growth in steps, prelude/summary preservation, and tool-call histories.
  • Codex-backed autoreview on the commit: clean, no accepted findings (0.96).
  • Both production callers inspected (attempt-history-prepare.ts, compaction-session-execution.ts); neither depends on exact-limit trimming.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Jul 28, 2026
@steipete
steipete marked this pull request as ready for review July 28, 2026 16:05
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 28, 2026
@clawsweeper

clawsweeper Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 28, 2026, 12:09 PM ET / 16:09 UTC.

ClawSweeper review

What this changes

This PR changes history trimming so channel sessions evict conversation turns in batches, keeping the prompt prefix stable for several turns to improve provider prompt-cache reuse.

Merge readiness

⛔ Blocked until real behavior proof from a real setup is added - 5 items remain

Keep this PR open for maintainer review. The cache-amortization approach is focused, but it changes the meaning of existing historyLimit and dmHistoryLimit settings by allowing up to 50% more user turns than configured, so it needs an explicit product/compatibility decision before merge.

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

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The patch is focused and tested at the pure-function level, but its effective setting-contract change and missing real runtime proof block merge confidence.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The PR body reports focused Vitest coverage, but it does not include after-fix evidence from a real channel or provider session showing restored cache reuse; redact any private endpoint, key, IP, or transcript details in such proof. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The PR body reports focused Vitest coverage, but it does not include after-fix evidence from a real channel or provider session showing restored cache reuse; redact any private endpoint, key, IP, or transcript details in such proof. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 4 items Configured-limit semantics change: The proposed limiter counts every user message and returns the complete conversation until a ceiling of ceil(limit × 1.5) is crossed. A user who configured a limit of four can therefore receive six turns in the provider prompt before eviction.
Focused regression coverage: The branch updates the focused limiter tests for the new threshold, stable-start, batched-cut, prelude, and tool-history cases; these are useful behavioral checks but do not demonstrate an after-fix channel or provider run.
Canonical bug linkage: The PR body explicitly identifies the open prompt-cache report as the problem it intends to fix, so that issue remains the canonical tracking item until this change is reviewed and merged.
Findings 1 actionable finding [P1] Preserve the configured history-limit contract before relaxing it
Security None None.

How this fits together

Channel and DM session settings feed a history-preparation step before each agent attempt. That step trims the message transcript used for provider requests and for compaction, affecting context size, token cost, latency, and prompt-cache stability.

flowchart LR
  A[Channel or DM session] --> B[History-limit setting]
  B --> C[Attempt history preparation]
  C --> D[Conversation history limiter]
  D --> E[Provider prompt]
  D --> F[Compaction input]
  E --> G[Cache cost and latency]
Loading

Decision needed

Question Recommendation
May existing historyLimit and dmHistoryLimit settings temporarily exceed their configured value by up to 50% in order to improve provider prompt-cache reuse? Retain strict limits: Keep the existing exact-cap contract and pursue cache improvements only through paths that do not enlarge the configured history window.

Why: This is not only an internal performance optimization: it changes the effective context cap selected by existing users and can alter provider cost, latency, and model context behavior.

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The PR body reports focused Vitest coverage, but it does not include after-fix evidence from a real channel or provider session showing restored cache reuse; redact any private endpoint, key, IP, or transcript details in such proof. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Preserve the configured history-limit contract before relaxing it (P1) - This changes existing historyLimit/dmHistoryLimit values from a hard cap to a lower bound: the limiter now returns all messages through ceil(limit × 1.5). Existing users can therefore send materially more context than they configured, so obtain an explicit owner decision and document or otherwise preserve the strict-cap behavior before merging.
  • Resolve merge risk (P1) - Existing users who selected a strict history limit may silently send up to 50% more user turns to a provider, changing context-budget, token-cost, and model-behavior expectations.
  • Resolve merge risk (P1) - The PR body provides focused unit-test evidence only; it does not show a redacted after-fix runtime trace demonstrating restored provider cache reuse in a real history-limited session.

Findings

  • [P1] Preserve the configured history-limit contract before relaxing it — src/agents/embedded-agent-runner/history.ts:64-69
Agent review details

Security

None.

PR surface

Source +17, Tests +55. Total +72 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 19 2 +17
Tests 1 66 11 +55
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 85 13 +72

Review metrics

Metric Value Why it matters
Existing limit semantics 2 existing settings changed; 0 new settings added Both channel history-limit settings can now admit up to 50% more turns than their configured value, which is a user-visible compatibility decision.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #115273
Summary: This PR explicitly presents itself as the candidate implementation for the open canonical prompt-cache report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Confirm the limit contract before merge (recommended)
    Obtain an owner decision on whether configured history limits may be exceeded, then align documentation, upgrade expectations, and real runtime proof with that decision.
  2. Accept relaxed limits deliberately
    Merge only if maintainers explicitly accept that existing configured limits become a lower bound rather than a hard maximum.
  3. Pause this approach
    Keep strict limit behavior and defer hysteresis if the compatibility tradeoff is not acceptable.

Technical review

Best possible solution:

Keep strict configured-limit semantics unless the responsible owner explicitly adopts bounded overage as the documented contract; if adopted, demonstrate fresh and upgrade behavior with a redacted real provider or channel trace that shows the intended cache improvement.

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

No high-confidence live reproduction is included. The source-level mechanism is clear from the supplied current behavior and focused limiter tests, but a real history-limited provider run has not been shown.

Is this the best way to solve the issue?

No—not until an owner decides whether an existing configured limit remains a hard cap. Batched eviction is a plausible cache optimization, but changing that contract silently is not the narrowest safe default.

Full review comments:

  • [P1] Preserve the configured history-limit contract before relaxing it — src/agents/embedded-agent-runner/history.ts:64-69
    This changes existing historyLimit/dmHistoryLimit values from a hard cap to a lower bound: the limiter now returns all messages through ceil(limit × 1.5). Existing users can therefore send materially more context than they configured, so obtain an explicit owner decision and document or otherwise preserve the strict-cap behavior before merging.
    Confidence: 0.93

Overall correctness: patch is incorrect
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 964c5abbded4.

Labels

Label changes:

  • add P2: This is a bounded but user-facing agent-context and cost behavior change for sessions using configured history limits.
  • add merge-risk: 🚨 compatibility: The branch changes the effective behavior of existing persisted history-limit settings without an explicit compatibility decision.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body reports focused Vitest coverage, but it does not include after-fix evidence from a real channel or provider session showing restored cache reuse; redact any private endpoint, key, IP, or transcript details in such proof. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Label justifications:

  • P2: This is a bounded but user-facing agent-context and cost behavior change for sessions using configured history limits.
  • merge-risk: 🚨 compatibility: The branch changes the effective behavior of existing persisted history-limit settings without an explicit compatibility decision.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body reports focused Vitest coverage, but it does not include after-fix evidence from a real channel or provider session showing restored cache reuse; redact any private endpoint, key, IP, or transcript details in such proof. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Configured-limit semantics change: The proposed limiter counts every user message and returns the complete conversation until a ceiling of ceil(limit × 1.5) is crossed. A user who configured a limit of four can therefore receive six turns in the provider prompt before eviction. (src/agents/embedded-agent-runner/history.ts:64, b5e509bc012f)
  • Focused regression coverage: The branch updates the focused limiter tests for the new threshold, stable-start, batched-cut, prelude, and tool-history cases; these are useful behavioral checks but do not demonstrate an after-fix channel or provider run. (src/agents/embedded-agent-runner.limithistoryturns.test.ts:104, b5e509bc012f)
  • Canonical bug linkage: The PR body explicitly identifies the open prompt-cache report as the problem it intends to fix, so that issue remains the canonical tracking item until this change is reviewed and merged. (b5e509bc012f)
  • Repository policy applied: The reviewed repository policy treats existing config/default behavior and changes that alter user settings as compatibility-sensitive, requiring an explicit upgrade-safe decision rather than assuming a new effective default is safe. (AGENTS.md, 964c5abbded4)

Likely related people:

  • steipete: The supplied PR and its linked canonical report both attribute the history-limit cache analysis and proposed hysteresis design to this contributor; current-main feature-history ownership could not be established from the available read-only inspection context. (role: proposed design author and related cache-report author; confidence: low; commits: b5e509bc012f; files: src/agents/embedded-agent-runner/history.ts, src/agents/embedded-agent-runner.limithistoryturns.test.ts)

Rank-up moves

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

  • Get an explicit owner decision on strict versus bounded-overage history limits.
  • Add redacted after-fix runtime evidence showing cache behavior for a history-limited session.

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.

@steipete
steipete merged commit d5dee71 into main Jul 28, 2026
186 of 196 checks passed
@steipete
steipete deleted the steipete/history-limit-hysteresis-115273 branch July 28, 2026 16:24
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Jul 28, 2026
…-20260728

* origin/main:
  fix(slack): cap chat.update edit text at the 4000-char limit, not the 8000 send limit (#115027)
  [AI-assisted] docs: recommend Node 26 in quickstart, landing, and platform install docs (#115064)
  refactor(workboard): tidy Control UI card execution helpers (#115195)
  perf(agents): amortize history-limit eviction with hysteresis (#115273) (#115281)
  fix: schema-version refusal blames a downgrade that never happened and cannot identify the stale install (#115232)
  fix: restore Fish completion after global CLI options (#115222)
  refactor(agents): collapse the client-tool catalog branch (#115212)
vincentkoc added a commit to LZY3538/openclaw that referenced this pull request Jul 28, 2026
* origin/main: (199 commits)
  refactor(workboard): tidy Control UI card execution helpers (openclaw#115195)
  perf(agents): amortize history-limit eviction with hysteresis (openclaw#115273) (openclaw#115281)
  fix: schema-version refusal blames a downgrade that never happened and cannot identify the stale install (openclaw#115232)
  fix: restore Fish completion after global CLI options (openclaw#115222)
  refactor(agents): collapse the client-tool catalog branch (openclaw#115212)
  fix(macos): signed rebuild no longer stalls on app shutdown (openclaw#103957)
  fix(agents): prevent repeated Code Mode output across waits (openclaw#115213)
  refactor(ui): split Profile (identity) from Usage (statistics) (openclaw#115245)
  fix(channels): report a channel that cannot receive as unhealthy instead of connected (openclaw#115229)
  fix(cli): reject malformed infer model refs (openclaw#115225)
  feat(ui): finish the Lobsterdex at 42 with wild variants, squish fix, and blink variance (openclaw#115264)
  test(migrations): avoid mtime precision in checkpoint fixture (openclaw#115269)
  test(signal): verify archive limits without malformed tar (openclaw#115270)
  refactor(sessions): isolate legacy transcript fixtures (openclaw#115231)
  fix(discord): clear pending launch watchdog (openclaw#115100)
  fix(agents): stop quadratic subagent prompt rendering (openclaw#115263)
  fix(memory-core): recover dreaming cron reconciliation (openclaw#115174)
  fix(qa-lab): filter incompatible channel scenarios (openclaw#115087)
  fix(android): respect locale in compact labels
  test(i18n): prove iOS discovery catalog ownership
  ...
vincentkoc added a commit that referenced this pull request Jul 28, 2026
…etwork-none

* origin/main:
  feat(skills): shared authoring standards make learned skills routable (#115103)
  fix(matrix): suppress previews for modifying hooks
  fix: prevent node gateway hangs and runaway local inference (#115248)
  refactor(ui): adopt @lit/task across remaining page surfaces (#115274)
  fix(slack): cap chat.update edit text at the 4000-char limit, not the 8000 send limit (#115027)
  [AI-assisted] docs: recommend Node 26 in quickstart, landing, and platform install docs (#115064)
  refactor(workboard): tidy Control UI card execution helpers (#115195)
  perf(agents): amortize history-limit eviction with hysteresis (#115273) (#115281)
vincentkoc added a commit to christian-lallo/openclaw that referenced this pull request Jul 28, 2026
* origin/main: (62 commits)
  feat(macos): enable Computer Control by default and diagnose stale Accessibility grants (openclaw#115280)
  fix(qa): restore full-stack scenarios and truthful suite exits (openclaw#115290)
  feat(memory): backfill past sessions from Control UI (openclaw#115266)
  docs: link macOS onboarding pages to app download (openclaw#111361)
  feat(skills): shared authoring standards make learned skills routable (openclaw#115103)
  fix(matrix): suppress previews for modifying hooks
  fix: prevent node gateway hangs and runaway local inference (openclaw#115248)
  refactor(ui): adopt @lit/task across remaining page surfaces (openclaw#115274)
  fix(slack): cap chat.update edit text at the 4000-char limit, not the 8000 send limit (openclaw#115027)
  [AI-assisted] docs: recommend Node 26 in quickstart, landing, and platform install docs (openclaw#115064)
  refactor(workboard): tidy Control UI card execution helpers (openclaw#115195)
  perf(agents): amortize history-limit eviction with hysteresis (openclaw#115273) (openclaw#115281)
  fix: schema-version refusal blames a downgrade that never happened and cannot identify the stale install (openclaw#115232)
  fix: restore Fish completion after global CLI options (openclaw#115222)
  refactor(agents): collapse the client-tool catalog branch (openclaw#115212)
  fix(macos): signed rebuild no longer stalls on app shutdown (openclaw#103957)
  fix(agents): prevent repeated Code Mode output across waits (openclaw#115213)
  refactor(ui): split Profile (identity) from Usage (statistics) (openclaw#115245)
  fix(channels): report a channel that cannot receive as unhealthy instead of connected (openclaw#115229)
  fix(cli): reject malformed infer model refs (openclaw#115225)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Prompt cache: historyLimit sliding window yields ~0% cache hits; evict in chunks with hysteresis

1 participant