Skip to content

fix: prevent context budgets widening after catalog discovery - #148596

Closed
jalehman wants to merge 2 commits into
mainfrom
openclaw/fix-148575-context-budget
Closed

jalehman wants to merge 2 commits into
mainfrom
openclaw/fix-148575-context-budget

Conversation

@jalehman

@jalehman jalehman commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge on hold: built-SDK metadata repair is confirmed, but live CLI widening was not reproduced. See Crabbox verification below.

Closes #148575

What Problem This Solves

Fixes runtime compaction budgets widening to a model's native context window when catalog loading drops its smaller active-input budget.

User Impact

Models retain their declared active-input budget after discovery, so preflight and the embedded runtime agree on the default budget. Explicit configured input caps, session-selected windows, and caller budgets retain their existing precedence. Native capacity remains separate; no configuration migration is needed.

Why This Change Was Made

The registry already receives contextTokens from model catalogs but omits it when creating runtime rows. Preserve that optional field in the schema, catalog projection, and dynamic provider registration instead of adding a provider-specific fallback or lowering native model capacity.

Evidence

  • Before the repair, the new source regressions fail for authored, generated, and registered models. The real registry → OpenAI resolver → normalization → embedded policy test reproduces runtime 1,050,000 versus preflight 272,000.
  • With the repair, 141 tests pass across seven focused files: registry sources, registry lifecycle/auth, the new provider-budget boundary, context-window guard, context-cache projection, embedded setup, and OpenAI dynamic models.
  • Controls cover larger/smaller configured input caps, native-capacity clamping, selected windows, caller budgets, fork/refresh replay, and deliberate native-only fallback.
  • Changed-file checks pass, including core/core-test typechecking, type-aware lint (zero warnings/errors), formatting, dead-export scans, plugin boundaries, and repository guards.
  • Independent autoreview: scoped-clean through P2.

The original focused tests were deterministic and credential-free. Additional Crabbox built-SDK and real OpenAI CLI results are documented below; no full repository test suite or production Gateway change was performed.


View the OpenClaw team session

Crabbox behavior verification

Built public SDK before/after proof confirms that this PR restores contextTokens=272000 while preserving native capacity 1050000. However, three real CLI baseline configurations already delivered 272000 to the context engine, so the claimed end-to-end widening was not reproduced. The merge is on hold pending a faithful affected-route reproduction or an explicit maintainer decision on the narrower metadata-preservation scope.

Detailed commands, environment, revisions, results, and limitations: #148596 (comment)

@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Sep 14, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 14, 2026, 8:14 PM ET / September 15, 2026, 00:14 UTC (Revision 3).

ClawSweeper review

What this changes

Preserves models’ active-input budgets through catalog loading, provider registration, and registry snapshots, with regression coverage for budget precedence.

Merge readiness

⛔ Blocked before merge - 4 items remain

The metadata repair remains useful and has convincing built-SDK before/after evidence, with no actionable patch defects found. Keep the explicit merge hold: the tested CLI routes did not reproduce widening, and the overlapping open PR is currently conflicted.

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

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, sound metadata repair with useful before/after proof; the broader runtime claim needs an explicit scope disposition.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The exact-head Crabbox built-SDK registry probe demonstrates the changed production owner preserving 272000 active-input tokens while retaining 1050000 native capacity. This is sufficient proof of metadata preservation; the separately reported real CLI runs do not prove widening and remain subject to the explicit scope decision.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The exact-head Crabbox built-SDK registry probe demonstrates the changed production owner preserving 272000 active-input tokens while retaining 1050000 native capacity. This is sufficient proof of metadata preservation; the separately reported real CLI runs do not prove widening and remain subject to the explicit scope decision.
Evidence reviewed 8 items Verified introduced change and current-main necessity: The pinned introduced delta contains only the registry and two test files. Comparing fetched main with the reviewed head confirms main still omits contextTokens from the schema, both runtime projections, and registration input.
Existing budget contract: The runtime model already defines contextTokens as an optional compaction/session budget distinct from contextWindow; the configuration schema and OpenAI setup documentation already support the field.
Production consumer and implementation boundary: The OpenAI resolver returns an exact registry row, and OpenClaw-owned embedded policy reads its active-input budget. The new test explicitly selects agentRuntimeId=openclaw and nativeModelOwned=false; neither this path nor the claimed API-key proof depends on the Codex runtime contract.
Findings None None.
Security None None.

How this fits together

The model registry turns provider catalogs and configured model definitions into runtime model records. Preflight and embedded execution consume those records to budget conversation context separately from native model capacity.

flowchart LR
  A[Provider catalogs] --> C[Model registry]
  B[Configured models and registrations] --> C
  C --> D[Runtime model metadata]
  D --> E[Preflight budget]
  D --> F[Embedded runtime policy]
  F --> G[Context assembly and compaction]
Loading

Decision needed

Question Recommendation
Should this PR land as a proven SDK metadata-preservation repair, or remain held until the reported CLI widening is reproduced? Accept the narrower metadata repair: Approve preserving the existing optional budget field, narrow the title and impact claims, and avoid automatically closing the unresolved runtime report.

Why: The author explicitly holds the merge, and the real CLI experiments contradict the broader regression claim while independently confirming the narrower SDK defect.

Before merge

  • Resolve merge risk (P1) - The faithful CLI route behind the reported widening remains unidentified; landing this patch must not imply that the broader compaction report has been verified or fully resolved.
  • Resolve merge risk (P1) - SDK consumers will begin receiving and honoring supplied active-input caps that were previously dropped, potentially compacting earlier; the maintainer should explicitly accept that narrower compatibility correction.
  • Complete next step (P2) - Resolve the explicit merge hold by accepting the narrower SDK repair or requiring affected-route runtime proof; align the PR claims and issue-closing intent with that choice.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +5, Tests +174. Total +179 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 5 0 +5
Tests 2 174 0 +174
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 179 0 +179

Review metrics

Metric Value Why it matters
SDK registration contract 1 optional budget field added; 0 required fields added Registration now carries an existing runtime-model field without requiring callers to change their input.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #148575
Summary: This PR is the linked candidate for the reported metadata loss; runtime impact remains unresolved, and another open PR overlaps the registry repair.

Members:

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

Merge-risk options

Maintainer options:

  1. Accept the documented budget semantics (recommended)
    Explicitly approve SDK consumers receiving the supplied cap, using the built-SDK comparison and precedence regressions as evidence for the narrow repair.
  2. Keep the scope decision on hold
    Pause landing while the affected runtime route and coordination with the overlapping PR remain unresolved.

Technical review

Best possible solution:

Preserve the existing budget field at its registry owner, accept its documented SDK semantics explicitly, and keep unverified runtime impact separate from the metadata fix.

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

Yes for metadata loss: current-main projections omit the existing field, and the supplied built-SDK comparison demonstrates it. No high-confidence end-to-end CLI widening reproduction is established; all three tested baseline routes retained the smaller budget.

Is this the best way to solve the issue?

Yes for the demonstrated metadata defect: forwarding the field through the existing registry is the narrowest repair. The evidence does not yet justify treating it as a complete fix for the reported CLI compaction behavior.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 9434fe6f0ad3.

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: The public registry API will preserve supplied caps that downstream consumers previously could not observe.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The exact-head Crabbox built-SDK registry probe demonstrates the changed production owner preserving 272000 active-input tokens while retaining 1050000 native capacity. This is sufficient proof of metadata preservation; the separately reported real CLI runs do not prove widening and remain subject to the explicit scope decision.

Label justifications:

  • P2: This is a bounded, demonstrated metadata-loss repair whose broader live runtime impact remains unverified.
  • merge-risk: 🚨 compatibility: The public registry API will preserve supplied caps that downstream consumers previously could not observe.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The exact-head Crabbox built-SDK registry probe demonstrates the changed production owner preserving 272000 active-input tokens while retaining 1050000 native capacity. This is sufficient proof of metadata preservation; the separately reported real CLI runs do not prove widening and remain subject to the explicit scope decision.
  • proof: sufficient: Contributor real behavior proof is sufficient. The exact-head Crabbox built-SDK registry probe demonstrates the changed production owner preserving 272000 active-input tokens while retaining 1050000 native capacity. This is sufficient proof of metadata preservation; the separately reported real CLI runs do not prove widening and remain subject to the explicit scope decision.

Evidence

What I checked:

  • Verified introduced change and current-main necessity: The pinned introduced delta contains only the registry and two test files. Comparing fetched main with the reviewed head confirms main still omits contextTokens from the schema, both runtime projections, and registration input. (src/agents/sessions/model-registry.ts:855, c625d360015d)
  • Existing budget contract: The runtime model already defines contextTokens as an optional compaction/session budget distinct from contextWindow; the configuration schema and OpenAI setup documentation already support the field. (packages/llm-core/src/types.ts:684, c625d360015d)
  • Production consumer and implementation boundary: The OpenAI resolver returns an exact registry row, and OpenClaw-owned embedded policy reads its active-input budget. The new test explicitly selects agentRuntimeId=openclaw and nativeModelOwned=false; neither this path nor the claimed API-key proof depends on the Codex runtime contract. (src/agents/sessions/model-registry.context-budget.test.ts:72, c625d360015d)
  • Built-SDK proof and contrary CLI evidence: The complete supplied comment at fix: prevent context budgets widening after catalog discovery #148596 (comment) reports independently built merge-base and exact-head SDK probes: the active budget changes from absent to 272000 while native capacity remains 1050000. Three real baseline CLI configurations already delivered 272000; the paired widening assertion failed. This proves metadata preservation, not the broader CLI regression. Captured context sourceRevision: cb26fd539929a6cefd90a12367bc30ce6d70ef306c56a378ec8795309d69a999. (c625d360015d)
  • Overlapping implementation remains open: fix(context): preserve provider-scoped prompt budgets before reply maintenance #141052 contains the same registry field-preservation changes plus ordinary reply-selection work. A live read reports open, unmerged, and mergeable=false, so it is not a safe supersession target. (src/agents/sessions/model-registry.ts, 08a2ade13cc8)
  • Latest-release check: The v2026.9.4 registry also omits contextTokens from these projections. Local release-object inspection failed because the object was unavailable; the read-only GitHub contents endpoint supplied the release source. (src/agents/sessions/model-registry.ts:752, 3a9d69db306c)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

Rank-up moves

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

  • Align the title, impact statement, and linked-issue closure intent with the scope the maintainer accepts.

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 (2 earlier review cycles)
  • reviewed 2026-09-14T23:18:04.163Z sha c625d36 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-14T23:38:07.489Z sha c625d36 :: needs maintainer review before merge. :: none

@jalehman
jalehman marked this pull request as ready for review September 14, 2026 23:31
@jalehman jalehman self-assigned this Sep 14, 2026
@jalehman

jalehman commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Crabbox before/after results: metadata repair confirmed; runtime widening not reproduced

I tested the built artifacts, then actual CLI agent turns against OpenAI. These are different proof levels and should not be conflated.

Environment and revisions

  • Provider: Blacksmith Testbox, selected by the existing Crabbox configuration (not direct AWS).
  • Lease: tbx_01m2h4815d8ycy0g4cy7w20ntq.
  • Environment/run: https://github.com/openclaw/openclaw/actions/runs/34909340742
  • Crabbox 0.48.1; Node 24.19.0; pnpm 12.3.4.
  • Before: 8b983db1859864173b8acaf1900771e0628aa57a (the PR merge base).
  • After: c625d360015db427626c8b3a24d2cef90f19fa28.
  • Both revisions independently installed with pnpm install --frozen-lockfile and built with pnpm build. The baseline was a detached temporary worktree, not an edit to the synced PR checkout.

Confirmed: built public SDK preserves the field after this PR

I imported ModelRegistry and AuthStorage from each build's openclaw/plugin-sdk/agent-sessions, created a registry from the shipped OpenAI manifest with empty config, and looked up gpt-6-astra.

Built revision row.contextTokens row.contextWindow
Before absent (null in diagnostic JSON) 1,050,000
After 272,000 1,050,000

The probe resolved the SDK from each revision's own dist/plugin-sdk/agent-sessions.js. This is executable built-artifact evidence of the registry repair, not just a source inspection.

Not reproduced: full CLI widening from 272k to 1.05M

An isolated receipt-only context-engine plugin recorded real assemble and durable commitTurn calls. It declared before-current-turn-entry-v1 fencing and atomic-idempotent-v1 turn advancement. The model requests went to the real OpenAI Responses API using the Testbox's hydrated OpenAI credential; no provider mock was used. Each case used separate temporary HOME/state/config/workspace directories and requested only BUDGET_PROOF_OK.

Observed case Build Durable runtimeContext.tokenBudget Native window Actual final reply / fallback
Configured Astra primary, explicit provider stanza Before 272,000 1,050,000 BUDGET_PROOF_OK / none
Configured Astra primary, no provider stanza Before 272,000 1,050,000 BUDGET_PROOF_OK / none
Sol primary, public --model openai/gpt-6-astra override Before 272,000 1,050,000 BUDGET_PROOF_OK / none
Configured Astra primary, explicit provider stanza After 272,000 1,050,000 CLI exit 0; reply marker found

All four observed CLI turns exited zero. Independently parsed baseline results confirmed openai/gpt-6-astra, the exact final reply BUDGET_PROOF_OK, aborted=false, and no fallback. The successful candidate engine probe captured the reply marker and the assembly/commit receipts; it did not independently assert all final metadata fields. The paired regression harness failed its expected-before assertion because the baseline delivered 272,000 rather than 1,050,000. Live 64k/922k control pairs were consequently not reached; their existing unit-test coverage is separate evidence.

Example baseline runtime-override receipts:

{"method":"assemble","tokenBudget":249832,"promptBudget":249832}
{"method":"assemble","tokenBudget":271985,"promptBudget":272000}
{"method":"commitTurn","runtimeBudget":272000,"nativeWindow":1050000,"messageCount":2}

Interpretation / merge status

The PR fixes a real, demonstrated metadata-loss bug. However, the live CLI paths above retain or recover the active budget elsewhere; these experiments do not establish which exact runtime route exhibits the widening described in #148575. The code has prepared/static model paths in addition to registry resolution, but the masking mechanism is not yet conclusively isolated.

I am holding the merge under the request to obtain faithful runtime before/after proof first, despite passing exact-head CI, 141 focused tests, and clean P2 reviews. Head-only success is not sufficient evidence of an end-to-end fix. The remaining decision is to identify and reproduce the affected runtime route, or explicitly accept the narrower built-SDK metadata-preservation proof and narrow the runtime claim accordingly.

No production Gateway configuration, credentials, or state was changed. The test engine is an observation fixture, not a validation of production lossless-memory compaction or a 272k-token workload.

Commands and built-SDK reproduction

The lease uses the repository's configured backend:

crabbox warmup --blacksmith-ref openclaw/fix-148575-context-budget --keep --timing-json
crabbox run --id tbx_01m2h4815d8ycy0g4cy7w20ntq --timing-json --shell -- '<isolated build/probe harness>'
# In each independently owned revision:
pnpm install --frozen-lockfile
pnpm build
# Live agent invocation in a separate temporary HOME/state/config/workspace:
node "$REPO/openclaw.mjs" agent --local --agent main --session-id "$UUID" \
  --message 'Reply with exactly BUDGET_PROOF_OK. Do not call any tools.' --json --timeout 120
# Per-run override variant adds: --model openai/gpt-6-astra
# Cleanup:
crabbox stop tbx_01m2h4815d8ycy0g4cy7w20ntq

Run this with node --input-type=module from each built repository root:

import fs from 'node:fs';
import { ModelRegistry, AuthStorage } from 'openclaw/plugin-sdk/agent-sessions';
const catalog = JSON.parse(fs.readFileSync('./extensions/openai/openclaw.plugin.json', 'utf8'))
  .modelCatalog.providers.openai;
const registry = ModelRegistry.create(AuthStorage.inMemory({}), 'captured:models.json', {
  config: {}, modelsJsonContents: null, pluginCatalogs: [], includePluginCatalogs: false,
  staticProviderConfigs: { openai: catalog },
});
const row = registry.find('openai', 'gpt-6-astra');
console.log({ contextTokens: row?.contextTokens ?? null, contextWindow: row?.contextWindow });

This last SDK probe exits zero and returns absent/272000 before/after as shown above. The live runtime comparison does not reproduce the expected-before widening and must not be reported as a successful regression proof.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Sep 15, 2026
@jalehman

Copy link
Copy Markdown
Contributor Author

Closing in favor of the pre-existing #141052, as requested by the maintainer. That PR already contains the same contextTokens registry-preservation repair, plus a separate ordinary-reply catalog fix. We will review the existing contribution rather than land a duplicate.

The built-SDK before/after evidence and its limitations remain available at #148596 (comment). It confirms metadata preservation, not the reported full CLI budget widening; three tested baseline CLI routes already retained the smaller budget. Closing this duplicate does not resolve #148575 or establish that #141052 is ready to merge.

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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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.

[Bug]: ModelRegistry drops contextTokens, widening Astra runtime budgets from 272k to 1.05M

1 participant