Skip to content

fix: native Codex session usage stays zero after /new - #133441

Merged
steipete merged 1 commit into
mainfrom
steipete/native-usage-handoff-625078
Aug 30, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/native-usage-handoff-625078

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Closes #133346 — native Codex turns leave fresh-zero usage after /new.

Related: #133260 — recovery compaction cancellation and committed-count accounting.

Additional instructions

Maintainers can edit this same-repository branch.

What Problem This Solves

Fixes an issue where users running native Codex turns would see zero or stale session usage after /new, even though the model returned a successful reply and positive usage. The dropped finalization also left the session's context-window metadata stale, making /status and the Sessions UI misleading.

Why This Change Was Made

The inner run correctly claimed a new session writer, but the private accounting handoff was emitted only after a compaction or an ordered context observation. Native runs can return valid usage without either event. The command therefore finalized against its pre-run working copy, and the existing exact-writer guard correctly rejected that stale identity.

Settlement now carries the already-claimed writer independently of context telemetry. An absent context snapshot permits the existing last-call usage calculation; an explicitly unknown snapshot invalidates freshness, while an observed zero remains a real zero. Both command and reply collectors preserve invalidation across opaque fallbacks. Writer checks, replaced/deleted-owner protection, cancellation accounting, and public/private boundaries remain intact—no latest-row authority adoption, new registry, schema, configuration, protocol, or dependency change.

The requested live verification also exposed stale fixtures: the embedded-cache helper supplied an unbound admission and contradictory agent-directory/database ownership, while the native client omitted the tool-event capability required by its own evidence assertions. Those fixtures now use real admission, consistent temporary ownership, and negotiated tool events before and after restart. The Anthropic post-compaction test checks identical marked-prefix/cache-policy snapshots and real cache reuse instead of assuming that 30% of a rewritten conversation must already be cached. Its prompts, provider/model selection, successful-compaction checks, response checks, and minimum actual cache reads remain unchanged.

User Impact

Completed native turns update their own token usage and effective context window without requiring a compaction event. Superseded runs still cannot overwrite another writer's session. Unknown post-compaction context stays unknown rather than borrowing stale usage.

Evidence

The regression test exercises real admission, SQLite writer claim, run settlement, command collection, and final persistence; only the native provider attempt is substituted. Against the original production code, the current-writer case fails after finalization at 0 versus 13,357 tokens, while the replaced-writer control passes. Both pass with the repair.

On the integrated candidate, 637 focused tests across nine files passed, followed by the complete changed-code gates, core/core-test typechecks, typed lint, import-cycle/ownership guards, and a full build. Fresh independent Codex review returned scoped-clean at its configured blocking-findings threshold.

Authenticated live proof used isolated per-case homes/state/config/native homes and only the selected CI-hydrated API key:

  • Native Codex API key: passed the original usage assertion, both four-compaction stress waves, exact event/result/persisted-count parity, real 300,000-byte native commands, hidden-marker recall, and an owned Gateway/app-server restart. The same native thread resumed with a different client. Persisted counts went 0 → 4, then 5 → 9 in the post-restart wave.
  • OpenAI AgentSession: two actual automatic compactions across five dense turns, followed by exact durable-marker recall.
  • OpenAI embedded cache: repeated real runner turns retained cache reuse.
  • Anthropic: actual manual compaction and a successful follow-up with more than 1,024 cached tokens. The final marked-prefix assertion verification is recorded below.

The final test-only delta passed on tree b7576b82854be131631433439415bceae72c8cd5 in a fresh Blacksmith Testbox tbx_01m19wf10jnmc3jve9cq5ypgxf (run 33326184977): complete core-test typechecking, targeted typed lint/formatting, a full build, and both selected Anthropic/OpenAI embedded-cache live cases. Anthropic compacted successfully, replied successfully, reused 2,212 cached tokens, and retained identical marked-prefix/cache-policy snapshots. Production and all other test files are byte-identical to the fully verified native/compaction candidate.

Full native/compaction proof used Blacksmith Testbox tbx_01m19rq9yz9j99a3bmnzk2s4h3, hydrated by run 33323141034. The externally executed command verdicts, not the hydration workflow's cleanup conclusion, are the proof. The initial full command correctly failed the uncalibrated Anthropic whole-request fraction; a diagnostic rerun proved identical marked-prefix/tool/model/cache-policy fingerprints and successful compaction with a 15.2% whole-request hit rate. Anthropic's cache contract matches previously written cumulative prefixes and promises no first-post-compaction percentage.

Real Control UI before and after

The same native API-key /new flow was run against the original and repaired production code with the real gateway-served Control UI enabled in a temporary diagnostic test copy. Normal dashboard authentication was used; no application-state injection, API mock, or authentication bypass. Existing assertions remained active: the original failed its fresh-zero check after capture, and the repaired case passed. Diagnostic source was restored byte-for-byte afterward. Every capture was inspected and contains only synthetic session data.

Before After
Before: successful native turn still shows zero session tokens After: the same flow shows 13,356 tokens and the native effective context window

The repaired UI shows 13,356 / 258,400 tokens. The original also retained the catalog's 272,000-token window because its metadata finalization was rejected; the repair persists the actual native window as well.

native-usage-after.mp4
Focused and live commands
pnpm test src/agents/agent-command.compaction-rotation.test.ts src/agents/agent-command.embedded-maintenance.test.ts src/agents/agent-command.live-model-switch.test.ts src/agents/command/session-store.test.ts src/agents/embedded-agent-runner/run.shared-integration.test.ts src/auto-reply/reply/agent-runner-execution-lifecycle.test.ts src/auto-reply/reply/agent-runner-result-accounting.persistence.test.ts src/auto-reply/reply/agent-runner-memory.test.ts src/auto-reply/reply/agent-runner.misc.runreplyagent.test.ts
pnpm build
OPENCLAW_LIVE_OPENAI_COMPACTION=1 OPENCLAW_LIVE_OPENAI_COMPACTION_FULL=0 pnpm test:live src/agents/sessions/agent-session.openai-compaction.live.test.ts
OPENCLAW_LIVE_CACHE_TEST=1 pnpm test:live src/agents/embedded-agent-runner.cache.live.test.ts -t 'preserves cache-safe shaping across compaction followup turns'
OPENCLAW_LIVE_CACHE_TEST=1 pnpm test:live src/agents/embedded-agent-runner.cache.live.test.ts -t 'keeps high OpenAI cache-read rates across repeated embedded-runner turns'
OPENCLAW_LIVE_CODEX_HARNESS=1 OPENCLAW_LIVE_CODEX_HARNESS_AUTH=api-key OPENCLAW_LIVE_CODEX_HARNESS_COMPACTION_STRESS=1 OPENCLAW_LIVE_CODEX_HARNESS_RESUME_STRESS_RESTARTS=1 pnpm test:live src/gateway/gateway-codex-harness.live.test.ts

The full node scripts/check-changed.mjs -- <changed paths> plan covered all 19 changed paths. The final test-only delta also receives the core-test typecheck and matching targeted typed-lint command. All application execution ran remotely; no operator gateway or state was used.

Scope and proof boundaries

Production: +70/−52 = +18 lines across eight files. Tests/test support: +334/−96 = +238 lines; docs: +2. The production growth separates an existing writer-ownership fact from optional telemetry while keeping one canonical handoff; the old telemetry-gated publication path is removed, not retained as a fallback.

Codex 0.151.0 contracts were inspected directly at upstream commit 78c290807ce710180111df227df3b7a4fe845452: exact optional response usage (core/src/session/turn.rs:2567, protocol v2/thread.rs:1834), last-request context and compaction recomputation (context_manager/history.rs:416, session/mod.rs:4155), and native command/event presentation (tools/handlers/shell_spec.rs:21, protocol v2/item.rs:286,901).

OAuth, Gemini, and full-window stress are not claimed by these runs. The native test used its existing reduced stress profile. No release/version publication or storage migration is part of this change.

Carry the claimed writer independently of optional ordered context telemetry. Preserve unknown/zero chronology and exact-writer fencing; repair live admission, directory ownership, tool-event capability and cache-contract fixtures.

Fixes #133346. Related to #133260.
@clawsweeper

clawsweeper Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Aug 30, 2026
@steipete
steipete marked this pull request as ready for review August 30, 2026 18:18
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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 Aug 30, 2026
@clawsweeper

clawsweeper Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 2:25 PM ET / 18:25 UTC.

ClawSweeper review

What this changes

The PR separates session-writer custody from optional context telemetry so successful native Codex turns persist their returned usage after starting a new session.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open for maintainer review: current main still has the telemetry-gated accounting path, while this maintainer-authored, maintainer-labelled PR supplies its proposed repair and substantial runtime evidence.

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

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Source review found no concrete introduced defect, with strong supplied boundary and live evidence; only the required direct upstream Codex contract inspection remains unavailable.
Proof confidence 🌊 off-meta tidepool Not applicable: This member-authored PR is exempt from the external-contributor proof gate; its supplied PR body nevertheless describes a real Gateway/native-Codex before/after run and retained-writer control, but the linked media could not be independently retrieved in this network-restricted review environment.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This member-authored PR is exempt from the external-contributor proof gate; its supplied PR body nevertheless describes a real Gateway/native-Codex before/after run and retained-writer control, but the linked media could not be independently retrieved in this network-restricted review environment.
Evidence reviewed 6 items Current-main behavior: The fetched current-main revision retains the conditional that emits no accounting fact unless compaction or a context snapshot occurred, which is the reported native-usage failure path.
Introduced owner-boundary repair: The PR now always carries a durable fact when an accepted writer exists, but keeps context observation optional; this lets final persistence derive valid last-call usage without weakening the exact-writer fence.
Caller and persistence path: Command post-run passes the captured accounting fact into the session updater, which uses an absent snapshot to derive usage and an explicit unknown snapshot to mark freshness stale.
Findings None None.
Security None None.

How this fits together

Native Codex turns settle through embedded-run accounting before the command or reply layer updates the SQLite-backed session row. Those counters feed status and session UI reporting while exact writer identity prevents superseded runs from changing the row.

flowchart LR
  A[Native Codex turn] --> B[Embedded run settlement]
  B --> C[Writer custody and context snapshot]
  C --> D[Command or reply accounting]
  D --> E[Exact writer validation]
  E --> F[Persisted session counters]
  F --> G[Status and Sessions UI]
Loading

Decision needed

Question Recommendation
Should this PR receive the final Codex-specific merge verdict only after the pinned upstream Codex source is available for direct contract inspection? Verify the pinned Codex contract: Make the pinned Codex source available and confirm the optional usage and context semantics before the final merge verdict.

Why: The source-level OpenClaw repair and supplied live evidence align, but repository policy requires direct sibling Codex inspection when judging the native runtime contract.

Before merge

  • Resolve merge risk (P1) - This changes persisted session-state accounting; direct inspection of the pinned Codex runtime/protocol source remains unavailable, so its native usage contract still needs maintainer-visible verification before a Codex-specific merge or proof verdict.
Agent review details

Security

None.

PR surface

Source +158, Tests +98, Docs +2. Total +258 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 9 212 54 +158
Tests 9 192 94 +98
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 406 148 +258

Review metrics

Metric Value Why it matters
Production versus test delta production +18/-52, tests/test support +334/-96, docs +2/-0 The production growth introduces the explicit custody-versus-observation distinction; the majority of the change is boundary and live-harness coverage.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #133346
Summary: This PR is the explicit candidate repair for the reproduced native session-usage bug; the earlier recovery-compaction PR is adjacent work with a distinct cancellation failure mode.

Members:

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

Merge-risk options

Maintainer options:

  1. Verify native accounting semantics (recommended)
    Confirm the pinned Codex source contract for optional response usage before merging this session-state persistence change.
  2. Accept the bounded risk
    A maintainer may accept the supplied live proof and exact-writer regression coverage without the local upstream-source check.

Technical review

Best possible solution:

Keep the writer-custody and optional-snapshot split, then verify it against the pinned Codex source contract before merging.

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

Yes—current-main source shows the missing accounting-fact path, and the supplied regression scenario exercises a claimed writer with native-style final usage and verifies both retained and replaced-writer outcomes.

Is this the best way to solve the issue?

Unclear—the custody/snapshot separation is the narrow owner-boundary repair from source review, but the dependency-backed native Codex contract could not be directly checked in the available environment.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: The change repairs inaccurate session-usage reporting on a native provider path without evidence of message loss, data loss, or an availability failure.
  • add merge-risk: 🚨 session-state: The PR changes how accepted runs update persisted token totals and freshness after session rotation.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This member-authored PR is exempt from the external-contributor proof gate; its supplied PR body nevertheless describes a real Gateway/native-Codex before/after run and retained-writer control, but the linked media could not be independently retrieved in this network-restricted review environment.

Label justifications:

  • P2: The change repairs inaccurate session-usage reporting on a native provider path without evidence of message loss, data loss, or an availability failure.
  • merge-risk: 🚨 session-state: The PR changes how accepted runs update persisted token totals and freshness after session rotation.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This member-authored PR is exempt from the external-contributor proof gate; its supplied PR body nevertheless describes a real Gateway/native-Codex before/after run and retained-writer control, but the linked media could not be independently retrieved in this network-restricted review environment.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Provide or make available the pinned Codex source snapshot so the native usage contract can be directly checked before the final merge verdict.

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

Copy link
Copy Markdown
Contributor Author

Land-ready verification

Reviewed head: c4ddff27161a0154e90f68289312b0f61b6bb8c5, exact tested tree b7576b82854be131631433439415bceae72c8cd5. Required openclaw/ci-gate is green in CI run 33327680338.

The owner-level repair removes settlement's telemetry-only publication gate. A claimed writer is handed to finalization even when the native turn emits no ordered context observation. The existing collectors distinguish absent, explicitly unknown, and measured-zero context; the exact-writer checks remain unchanged. A latest-row reread would adopt someone else's authority, and a second ownership callback would duplicate the existing handoff, so neither was added.

ClawSweeper request addressed: pinned Codex source

I personally inspected the sibling Codex source at the pinned 0.151.0 revision 78c290807ce710180111df227df3b7a4fe845452, rather than relying on generated OpenClaw types or another review:

This resolves the dependency-verification risk and Rank-up move in the latest ClawSweeper review; no code finding remains. No schema, config, protocol, dependency, public SDK, or writer-authorization change is needed.

Observed proof

The real admission → SQLite writer claim → settlement → command collector → finalizer regression fails against original production at 0 versus 13,357 tokens; the replacement-writer control passes. Both pass with the repair. 637 focused tests across nine files, full changed gates/typechecks/lint, and builds passed. Fresh independent Codex autoreview of the final tree returned scoped-clean at its configured blocking threshold.

Authenticated proof on isolated Blacksmith Testboxes covered native API-key usage, two four-compaction waves with 300,000-byte commands, event/result/persisted-count parity, hidden-marker recall, and a real Gateway/app-server restart with same-thread/different-client resume. Counts were 0 → 4, then 5 → 9. OpenAI AgentSession compacted twice and recalled its marker. Final Anthropic compaction/follow-up reused 2,212 cached tokens with identical populated marked-prefix/cache-policy snapshots; the OpenAI embedded-cache sibling passed too. Native proof environment, final cache proof environment. These links identify hydration environments; externally executed command results are detailed in the PR body.

The PR's inspected real Control UI captures show original 0 / 272000, repaired 13356 / 258400, with normal authentication and synthetic state. The original assertion failed after capture; the repaired native case passed. All owned proof environments are stopped.

Exact focused/live commands and before/after media are in the PR body. The final test-only delta also passed:

node scripts/run-tsgo-core-test-shards.mjs
node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/agents/embedded-agent-runner.cache.live.test.ts
pnpm build

Application execution was remote only. Production is +70/−52 = +18 LOC; tests/support +334/−96 = +238; docs +2. The remaining production growth expresses snapshot presence and same-writer folding inside the existing flow, not a new manager or fallback. OAuth, Gemini, and full-window performance are not claimed; native stress used its existing reduced-window profile. Proceeding through native prepare/merge without bypassing required checks.

@steipete
steipete merged commit e1adae3 into main Aug 30, 2026
311 checks passed
@steipete
steipete deleted the steipete/native-usage-handoff-625078 branch August 30, 2026 18:49
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

steipete added a commit that referenced this pull request Aug 30, 2026
Remove redundant outer ownership state and parameter adapters after the recovery and native-usage repairs (#133260, #133441). Reuse logical-writer comparison, lazy loaders, and resolved runtime facts while preserving fencing, chronology, and standalone subscription behavior. Consolidate test setup without dropping cases.

Validation: 902 focused tests, full changed-code gates, build, and independent Codex review. Net -45 production and -45 test/support lines.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
Carry the claimed writer independently of optional ordered context telemetry. Preserve unknown/zero chronology and exact-writer fencing; repair live admission, directory ownership, tool-event capability and cache-contract fixtures.

Fixes openclaw#133346. Related to openclaw#133260.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
Remove redundant outer ownership state and parameter adapters after the recovery and native-usage repairs (openclaw#133260, openclaw#133441). Reuse logical-writer comparison, lazy loaders, and resolved runtime facts while preserving fencing, chronology, and standalone subscription behavior. Consolidate test setup without dropping cases.

Validation: 902 focused tests, full changed-code gates, build, and independent Codex review. Net -45 production and -45 test/support lines.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Native Codex turns leave fresh zero usage after /new

1 participant