Skip to content

fix(context): respect accepted model limits in turns and compaction - #138087

Closed
zhangguiping-xydt wants to merge 82 commits into
openclaw:mainfrom
zhangguiping-xydt:fix/problem-context-tokens-bundled-catalog-fallback
Closed

zhangguiping-xydt wants to merge 82 commits into
openclaw:mainfrom
zhangguiping-xydt:fix/problem-context-tokens-bundled-catalog-fallback

Conversation

@zhangguiping-xydt

@zhangguiping-xydt zhangguiping-xydt commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Accepted model limits could be lost or combined with an unrelated runtime's limits during context budgeting, CLI preparation, and compaction.

User Impact

Turns and compaction use accepted provider capacity while respecting genuine native windows and explicit user caps. CLI-native runtimes retain their own limits. No new configuration, database fields, or migration is introduced.

Why This Change Was Made

The core Copilot discovery fix has landed. This follow-up carries those facts through shared budget consumers and refreshes the in-memory projection after accepted catalog publication. Startup prewarming consumes already prepared facts behind readiness and idle-work admission.

This PR already targets main and has no merge conflicts. Core discovery and persistence remain owned by main; saved-session provenance and accounting remain separate changes.

Evidence

Current head: 6e35c691f2919c4313c4ed802bb87368857ee6a3. Incorporates main 058cebea8e94 with a conflict-free merge, preserving the separate 19-file budget change. Five additional files carry the small CI repairs below.

  • Both accepted ClawSweeper code findings are addressed: remove the retired projection argument and provide the current-owner method in the cancellation fixture, so it exercises cancellation rather than an unrelated missing-method exception.
  • Scoped production lint, core production types, and diff checks passed on the unchanged production input. The agents-root test-type graph passed with the corrected fixture.
  • Earlier integrated checks passed 94 cases across five files. Those remain prior-input results; the corrected cancellation case's local replay was interrupted after its worker blocked in a filesystem rename. The unfinished embedded/CLI batch is not counted as passing.
  • Fresh independent review of the integrated production patch had no actionable P0-P2 findings. The later fixes remove an unused argument and repair the typed fixture.
  • The isolated authenticated Copilot attempt reached a healthy Gateway but failed before inference because the copied test agent state required the existing schema25-to26 session-identity migration. That migration is not introduced by this PR. Live budget/cap-removal proof is incomplete; current-head Windows proof is not claimed.
  • Prior UI CI failure is independently reproduced on main run 38180826485, job 114592980204: the same board-note assertion at board-mcp-app.e2e.test.ts:579. The causal board test and sandbox inputs are unchanged by this PR.
  • Previous-head CI failed only the wrapper inventory duplicate assertion and its aggregate gate. Main commit 2b66ae6c3a3 fixes the producer inventory; this head includes it. Direct execution of the actual copyPrWrapperSources boundary passes with 2,296 entries and zero duplicates. No test expectation or guard was weakened.
  • Previous-head CI run 38217941201 passed 75 checks but failed the built-CLI SQLite lifecycle test during concurrent session deletion. A focused real-controller regression reproduces the cancellation-ordering defect on main: broad reply cleanup makes the controller non-abortable before canonical cancellation records its stop reason. This head commits canonical active and pending cancellation before broad cleanup, retaining queued-first ordering and live-authority checks. The production fix only relocates the existing callback.
  • Focused cancellation proof: original three regression failures; final two suites 52/52 pass in 60.08s maintained-wrapper wall time (51.92s test time), using one worker. Existing cases were strengthened, not added. Fresh P0–P3 review found no issues (.93); formatting and diff checks pass. Local scoped lint was blocked by the borrowed-dependency physical-input guard; exact-head CI supplies that gate. Reset’s existing case passed separately before a mechanical named-test cleanup.
  • Includes the same independently reviewed session-fork fixture repair as the cron extraction PR: pristine main reproduces the obsolete one-SQL-read assertion, while two fresh authority reads are required. Only SQL-count instrumentation is removed; all outcomes and foreign-write guards remain. Original 32 pass/one fail; fixed 33/33 pass in 141.79s wall time. No production read/cache changed and no new test cases/CI seconds added.
  • The previous composed head passed build-artifacts job 114717283233, including the real built-CLI lifecycle proof. Its remaining two failures were test cutover issues: unsafe property access on an unknown dedupe entry and an old active-after-cleanup expectation. This head fixes both without casts or production changes. The full authorization/queue suites pass 48/48 in 33.02s wrapper wall time with one worker; fresh P0–P3 review is clean (.97).
  • Final-head CI run 38222150026 completed with 50 successful jobs, including build-artifacts and its real built-CLI lifecycle proof. The related test shard and test-type failures are cleared. The sole substantive red is the unrelated tooling suppression inventory (checks-node-compact-small-1, job 114721152095): it observes 19 entries but expects 18 because main’s managed cleanup helper has a Bun fd-connect suppression. A clean checkout of current main ccb7b5f7e5de reproduces the identical failure (three tests pass, one fails, 7.70s wrapper wall time). Neither inventory owner is changed by this PR. No baseline exception, suppression, skip, or rerun was introduced; the aggregate gate remains red for that inherited failure. No merge requested; auto-merge is disabled.

@clawsweeper

clawsweeper Bot commented Sep 4, 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: M labels Sep 4, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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. labels Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR carries accepted model capacity through context budgeting, CLI preparation, compaction, and publication-driven cache refresh.

Example: A model reports 872,000 usable prompt tokens while its 128,000-token native-window estimate is marked synthetic.

  • Before: Compaction loses the synthetic marker and uses a 128,000-token ceiling.
  • After: Compaction uses 872,000 tokens, subject to genuine native limits and explicit user caps.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful, source-supported implementation with no open code finding, but the required behavior-proof gate remains unsatisfied.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Turns and compaction can use an estimated or unrelated runtime limit instead of the selected model's accepted capacity.
Reason: The remaining owned-source failures are concrete, and the shared repair retains existing configuration and native transport contracts.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this PR retains distinct, maintainer-engaged budget work beyond the merged discovery and reporting fixes; no actionable introduced defect was found.

Priority: P2
Reviewed head: 6e35c691f2919c4313c4ed802bb87368857ee6a3

Before merge

  • Add real behavior proof - The earlier Windows turn and inspected SQLite/cold-process trace support their recorded revisions, while the latest authenticated attempt stops before inference. Provide redacted terminal output or logs through the shipped CLI/Gateway showing accepted capacity in a turn and compaction, refresh after catalog publication, native-runtime isolation, a 64,000-token authored cap and its removal, and fresh-state plus v2026.10.2 settings/history continuity. Redact IPs, API keys, phone numbers, and non-public endpoints. 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.

Findings

None.

Tests

  • Missing end-to-end proof: The remaining gap is a shipped CLI/Gateway run of the changed budget flow, including compaction, publication refresh, native-runtime isolation, cap removal, and stable-state continuity.
Agent review details

How this fits together

Prepared model catalogs supply capacity facts to shared context resolvers; embedded turns, CLI runtimes, and compaction consume the resulting budgets, while Gateway publications refresh their in-memory projection.

flowchart TD
  A[Accepted model catalog] --> B[Context cache projection]
  C[Authored model limits] --> D[Shared context resolver]
  B --> D
  D --> E[Turn preparation]
  D --> F[Compaction budget]
  G[Native runtime facts] --> E
  H[Catalog publication] --> B
Loading

Technical review

Best possible solution:

Use accepted capacity consistently across turns and compaction while preserving genuine ceilings, authored caps, and native-runtime ownership.

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

Current-main source shows the compaction handoff omitting the synthetic marker and the cache resolver treating that estimate as a ceiling; the added cases cover these inputs, but no target code was executed during this review.

Is this the best way to solve the issue?

The existing budget and catalog owners are appropriate: the patch preserves capacity provenance, excludes unrelated native-runtime rows, and passively refreshes accepted publications without starting provider discovery.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 2fc20b367b69.

Provenance checked

  • Configured context ceilings changes intended behavior with a stated reason (acef89b: Clamp configured input caps to model windows while preserving exact-row selection; this PR explains its additional distinction between genuine native capacity and synthetic estimates.)
  • Gateway context prewarm keeps the original intent (bf7840f: Keep post-ready projection cooperative and avoid acquiring full discovery; the new read consumes already accepted inventory and retains batched projection.)
  • Native authored-cap handoff keeps the original intent (6cc72f9: Send only the exact authored contextTokens value to native transports, leaving uncapped models without an override.)
  • CLI alias-aware context selection keeps the original intent (c75be4f: Preserve requested and normalized model identities through consolidated preparation; this PR retains their minimum owned limit while excluding API-cache capacity.)
  • Session cancellation authority keeps the original intent (da27b33: Bind Stop to the original caller and revalidate each effect; the ordering repair retains those checks while recording canonical cancellation before broad cleanup.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +249, Tests +426, Other -1. Total +674 across 24 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 11 331 82 +249
Tests 12 515 89 +426
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 24 846 172 +674

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Incorrect capacity budgeting can cause premature compaction or misleading runtime limits, with a bounded model-dependent impact.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (49 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-11T00:54:01.910Z sha 619e204 :: needs real behavior proof before merge. :: [P1] [P1] Keep metadata windows out of the native authored-cap handoff
  • reviewed 2026-10-11T02:29:39.075Z sha c3d80d5 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-11T02:40:16.432Z sha c3d80d5 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-11T22:21:39.730Z sha bb1ec1c :: needs real behavior proof before merge. :: [P2] [P2] Remove the obsolete prewarm projection callback | [P2] [P2] Give the cancellation fixture a valid current owner
  • reviewed 2026-10-11T22:36:54.097Z sha ed32ec3 :: needs real behavior proof before merge. :: [P2] Give the cancellation fixture a valid current owner
  • reviewed 2026-10-12T01:48:25.867Z sha 27b1b29 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-12T07:38:23.167Z sha 2d6c3a8 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-12T07:54:37.902Z sha 2d6c3a8 :: needs real behavior proof before merge. :: none

Reviewed October 12, 2026, 4:43 AM ET / 08:43 UTC (Revision 50).

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed 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. proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 5, 2026
@zhangguiping-xydt
zhangguiping-xydt force-pushed the fix/problem-context-tokens-bundled-catalog-fallback branch from 8816856 to c06ccf0 Compare September 5, 2026 19:54
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 5, 2026
@snotty

snotty commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

September 7 continuation for this PR's existing owner: a current-main-compatible fork branch now preserves your original commits in ancestry and carries the remaining producer/scope fixes plus upgrade proof. No successor PR, push to your branch, or upstream merge. #141052 remains separate and unchanged.

Source and adoption

Your exact c06ccf0665b24353b030193d8b2006f6ec5b68fd is verified in this branch's ancestry. Adoption can preserve that history; the consolidated follow-up also cherry-picks onto the main-refreshed owner checkpoint. It is not a claim that every hunk applies blindly to the older head. The earlier scope-only patch directly applicable to c06ccf remains available. Original authorship is retained without inferred coauthors. The earlier recovery branch/history is left intact, not force-pushed away.

Upgrade and producer proof

PASS on the exact clean source head281a129: secretless hosted run34120617149. Two intended early-scope RED cases plus five producer/error RED cases were reproduced against the refreshed owner baseline, followed by 804/804 GREEN tests across21 explicitly verified files. The complete changed-file repository gate passed: core production and all core test type programs, lint/format, dead exports, boundaries, native/schema and remaining selected guards, zero runtime import cycles, and git diff --check. The full serialized pnpm build also passed.

The follow-up itself is14 files, with production+71/-34 and tests+121/-2. Initial verification routing omissions were corrected by consulting canonical owner/auto-curated fast lanes and asserting every requested root appeared; fixture type and redundant-clone lint findings were fixed without widening schemas or suppressing rules. No earlier failed run is being represented as green.

The unmocked trace uses production discovery projection and command accounting, real isolated SQLite persistence, and a separate cold Node process. Model metadata is synthetic; there is no provider call or operator-session mutation.

warm discovered/model-owned budget: 654321
persisted source:                   resolved-v1
fresh cold process:                 654321 / resolved-v1
same legacy resolved row:           rejected (undefined)
provider/model/harness mismatch:    rejected in all three cases
current authored cap:               64000 / resolved
changed authored cap:               96000 / resolved
removed cap + current metadata:     654321 / resolved-v1
removed cap + no current metadata:  old configured value not resurrected

The serialized source fields and source literals already exist; no session schema or migration is introduced. Native harness-owned policy stays private. Explicit runtime telemetry remains authoritative, and missing old producer tags are not relabeled.

A read-only test merge against inspected main e9a2a0298557451d28704b900bf3c4dfb0a4a99d is clean, with no intervening main changes on the touched paths. This is separate from the exact e3-based CI proof; no unnecessary rebase was performed.

Remaining boundary — deliberately not guessed

The same production-module audit still shows a generic scoped cache of 128000 beating supplied scalar modelContextTokens: 872000 / modelContextWindow: 1000000. Those inputs do not carry a selected-credential provenance discriminator. A lower verified discovery value must also continue to beat a larger static fallback, so choosing the larger number or trusting every supplied numeric argument would violate a sibling contract.

This continuation does not claim that early stale-cache-versus-selected-live ownership is fully repaired. The existing selected-credential runtime preparation/rematerialization machinery is preserved, and its siblings are covered. A credential-owned prepared-fact handoff before early maintenance remains a focused owner follow-up. No unconditional per-turn network discovery is added, and this is not evidence that all local hotfixes can be retired.

Required isolated autoreview was attempted but the Codex CLI is not logged in; no auth changes were made and no independent clean verdict is claimed. Tests and the production trace are not live inference-capacity proof.

The one-time coordination question is already posted. I will check responses before a successor decision and hold until September 11, 10:40 UTC / 18:40 SGT unless a maintainer explicitly invites one sooner. This branch does not close or supersede your PR.


September 11 source-only follow-up

Rechecked the complete issue/review conversations and timeline, including edited comments, and inspected your current head cc2e02aa64a33b5fa7d85071feeaf0bde857b65b. Your September 8 update is active author work: I am keeping coordination here, not opening a context successor or changing your branch. #141052 remains separate at fab8d8726a0aaf9bdd3f71081060d71a7373b569.

Current-main comparison (520bf609efacf80918d84c9a196288b646076574):

  • The authored-window ownership-tie correction at your current head is distinct from the older September 7 checkpoint. My earlier test counts/proof remain tied to their explicitly recorded heads; they were not rerun on your new head.
  • Main now includes #144009 (exact configured-row precedence) and #144168 (effective caps clamped to native windows). A refresh should preserve these contracts rather than blindly apply the old continuation.
  • #142871 supplies runtime model-budget facts to durable context-engine commits/recovery; it does not replace this PR's cold catalog resolver or SessionEntry provenance path. Main's command finalizer still uses the numeric resolver and defaults missing source to resolved.
  • I read the September 9 exact-head review and confirmed its test-only resolveMemoryFlushContextWindowTokens observation against source. Production maintenance uses model-selection-context.ts; the relevant regression belongs at that existing maintenance boundary. The review already acknowledges the linked SQLite/cold-process upgrade evidence, so I am not requesting duplicate proof.

The selected-credential live-metadata versus generic scalar-cache ownership gap described above remains separate; number comparisons alone do not justify raising a budget. No unconditional discovery, maximum-of-values workaround, session migration, merge, or closure is proposed here.

@snotty

snotty commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

@zhangguiping-xydt — would you prefer cherry-pickable follow-up commits for this PR, or a credited successor branch/PR for maintainer review?

I can prepare the scope fix already linked above plus old/new session compatibility proof (legacy resolved rejection; exact provider/model/harness resolved-v1; authored cap change/removal) and the remaining runtime producer/source-precedence work, preserving your resolution-owner design. #141052 stays independent; no unconditional per-turn discovery.

I will prepare only a fork branch for now, not push your branch or open a duplicate PR. I will check your response before any successor decision and wait until September 11, 10:40 UTC (18:40 SGT), unless a maintainer explicitly invites one sooner. This is coordination, not an inference about activity from PR age. Existing evidence: #138087 (comment) .

@RomneyDa

Copy link
Copy Markdown
Member

/allow-security-sensitive-change

1 similar comment
@RomneyDa

Copy link
Copy Markdown
Member

/allow-security-sensitive-change

@snotty

snotty commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

Additional source/guard evidence; budget scope unchanged

I kept your existing budget/resolution owner intact and contributed the reporting-specific coverage to #165991 instead: one-file regression commit fbfa840f2b49, six new cases, zero production changes. No cherry-pick of a duplicate reporting implementation and no edit to your branch.

Fresh secretless/no-egress checks on your unchanged exact head c3d80d522fce8e22195db91542948b7b48ac6ddf pass 16/16 context cases plus 33/33 native-window guards (8.43s and 2.76s wall respectively). These retain the synthetic-versus-genuine native-window distinction, authored caps and native/API owner separation through the real source owners.

The separate reporting owner-reversion control shows four expected failures/12 controls before its existing opt-out and 16/16 after, while omitted-flag execution cache lookup remains conservative. Keeping reporting facts separate must not silently alter this PR's execution/compaction policy.

Sanitized proof, exact revisions, commands and test patch: https://gist.github.com/snotty/5030d0d5ca970b0ade000e3a9d7b4c64 . Counts belong to their recorded heads, not to a whole stack or today's main. These tests do not close the existing hosted CI/security, Windows/Copilot, upgrade, Telegram or provider-admission/integration gates; the PR remains unmerged.

@steipete

Copy link
Copy Markdown
Contributor

Thanks @zhangguiping-xydt for this. The context-limit problems it targets are now fixed on main through other changes:

We re-verified on current main through the real Gateway and CLI. A local Qwen3 4B turn with a 16k cap answered and compacted within that cap, and a native-runtime turn reported its own capacity rather than an API default. Closing as superseded; thanks again for digging into this. If you still see a limit ignored on current main, please reopen with the config and turn details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL 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.

6 participants