Repository navigation
fix: native Codex session usage stays zero after /new - #133441
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 2:25 PM ET / 18:25 UTC. ClawSweeper reviewWhat this changesThe PR separates session-writer custody from optional context telemetry so successful native Codex turns persist their returned usage after starting a new session. Regression provenancePossible regression — probable (reviewed change; failure trace). No predecessor PR is attributed. Merge readinessKeep 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 Review scores
Verification
How this fits togetherNative 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]
Decision needed
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
Agent review detailsSecurityNone. PR surfaceSource +158, Tests +98, Docs +2. Total +258 across 19 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest 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. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
|
Land-ready verificationReviewed head: 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 sourceI personally inspected the sibling Codex source at the pinned
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 proofThe 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.mjsnode scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/agents/embedded-agent-runner.cache.live.test.tspnpm buildApplication 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. |
|
Merged via squash.
|
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.
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.
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.
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/statusand 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:
The final test-only delta passed on tree
b7576b82854be131631433439415bceae72c8cd5in a fresh Blacksmith Testboxtbx_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
/newflow 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.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.tsOPENCLAW_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'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.0contracts were inspected directly at upstream commit78c290807ce710180111df227df3b7a4fe845452: exact optional response usage (core/src/session/turn.rs:2567, protocolv2/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, protocolv2/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.