Skip to content

fix(sessions): keep the usage anchor across a stopped run's abort marker - #176969

Closed
leapdragon wants to merge 1 commit into
openclaw:mainfrom
leapdragon:fix/preflight-usage-anchor-after-abort
Closed

leapdragon wants to merge 1 commit into
openclaw:mainfrom
leapdragon:fix/preflight-usage-anchor-after-abort

Conversation

@leapdragon

Copy link
Copy Markdown
Contributor

Summary

The transcript usage tail scan (session-transcript-accounting-policy.ts) treats any assistant message whose usage is stamped contextUsage: { state: "unavailable" } with zero token counts as a barrier: it stops scanning and discards the trailing messages, leaving the preflight with no usage anchor. The gateway stamps exactly that on the host-authored partial it appends when a run is stopped (chat-transcript-inject.ts, openclawAbort), so the first prompt after every abort falls back to estimating the whole raw transcript projection.

On a session owned by a lossless context engine the raw transcript is never trimmed, so that estimate is far above what the model sees. On the reporting host (lossless-claw, 262k window) the preflight saw about 460k tokens while the model's own usage was 45 to 73k, and on every post-abort turn it ran the pre-compaction memory flush (4 to 5 minutes of prefill on the flush model) plus a forced engine compaction that the engine itself reported as unnecessary (shouldCompact=false).

The abort marker carries no model call: its unavailable usage is there so the persisted session total gets re-derived, not because the context after it is unknown. The previous usage anchor plus the messages appended since (the partial included) still bounds the next prompt.

Change

  • isGatewayInjectedAbortMarker (message.openclawAbort.aborted === true) exempts the stopped run's partial from the unavailable-context barrier; it is counted as a trailing message over the previous anchor instead.
  • Every other unavailable snapshot keeps its barrier semantics (the existing "stops at unavailable context and accepts only a later valid transcript snapshot" test is unchanged).

Tests

New session-transcript-accounting-policy.test.ts:

  • keeps the previous usage anchor across a gateway-injected abort marker (prompt 72,912, trailing = the partial)
  • still treats an unavailable snapshot without the marker as a barrier
  • prefers a later real usage snapshot over the anchor kept across an abort

Also ran agent-runner-memory*.test.ts and memory-flush.test.ts (all passing), tsgo, oxlint, oxfmt.

Observed sequence (before)

Turn Preceded by abort memory_flush preflight_compaction Engine decision
1 yes skipped (same cycle) 76 s storedTokens 73,317, observedTokens 457,526, shouldCompact=false, forced
2 yes skipped 13 s 28,188 / 460,516, forced
3 yes 314 s 333 s 27,808 / 462,529, forced
4 yes 233 s 246 s 26,674 / 463,773, forced

Every turn not preceded by an abort prepared in under 2 s. The forced compaction re-arms the "one flush per compaction" guard, which is why the flush repeated.

Follow-up (not in this PR)

When no usage anchor exists at all, estimatePromptTokensFromSessionTranscript still estimates the full model-context projection, which overstates sessions owned by a context engine. That fallback could consult the engine or cap the projection, but it is a larger change and the abort case was the one hitting it every day.

🤖 Generated with Claude Code

The transcript usage tail scan treats any assistant message whose usage is
stamped `contextUsage: unavailable` with no token counts as a barrier: it
stops scanning and discards the trailing messages, so the preflight has no
usage anchor at all. The gateway stamps exactly that on the host-authored
partial it appends when a run is stopped (`chat-transcript-inject.ts`), so
the first prompt after every abort falls back to estimating the whole raw
transcript projection.

On a session owned by a lossless context engine the raw transcript is never
trimmed, so that estimate is far above what the model actually sees (about
460k tokens against 45 to 73k real on a 262k-window session) and the host
runs the pre-compaction memory flush plus a forced engine compaction on the
next turn, every time the user stops a run. On this host each of those turns
cost 4 to 5 minutes of flush prefill on the configured flush model.

The abort marker carries no model call: its unavailable usage exists so the
persisted session total is re-derived, not because the context after it is
unknown. Treat it as trailing growth over the previous usage anchor instead
of a barrier. Other unavailable snapshots keep their barrier semantics.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clawsweeper

clawsweeper Bot commented Oct 19, 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 triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. size: S labels Oct 19, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Preserve the previous transcript usage anchor when scanning past a Gateway-authored abort partial.

Example: A transcript contains a 72,912-token prompt usage snapshot followed by a Gateway-injected abort partial.

  • Before: The abort partial clears the usage anchor, causing preflight to estimate the full transcript.
  • After: The scan retains the 72,912-token anchor and counts the partial as trailing growth.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation is focused and source-supported, but the required after-fix production behavior has not been demonstrated.
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: Stopping a run can make the next prompt trigger unnecessary memory flushing and forced compaction in long sessions.
Reason: The targeted abort-marker failure is concrete and the change stays within the existing accounting owner; the broader no-anchor fallback remains a separate problem.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 1 item remains

This PR addresses a concrete accounting failure still present on current main, and its narrow exception preserves ordinary unavailable-usage barriers; no introduced correctness defect was identified.

Priority: P2
Reviewed head: f1f8681fe1cf82ab41891892dd05974b9501ee70

Before merge

  • Add real behavior proof - The added tests exercise the accounting function directly, and the reported live observations describe only the failure before the fix; please supply redacted Gateway logs or terminal output from a stopped run followed by another prompt, showing the retained anchor and resulting preflight decisions, with IPs, API keys, phone numbers, and non-public endpoints removed. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.

Findings

None.

Tests

  • Missing end-to-end proof: Provide an after-fix Gateway stop-and-next-prompt trace showing anchor retention and no unnecessary flush or forced compaction; base-red/head-green regression execution is also not documented.
Agent review details

How this fits together

Gateway cancellation persists an assistant partial; the shared transcript accounting policy reads stored events and supplies usage anchors and trailing messages to preflight token estimation.

flowchart TD
  A[Stopped Gateway run] --> B[Persisted abort partial]
  B --> C[Shared transcript accounting]
  D[Earlier provider usage] --> C
  C --> E[Preflight token estimate]
  E --> F[Memory flush and compaction decisions]
Loading

Technical review

Best possible solution:

Keep abort partials as trailing growth in the existing shared accounting owner while preserving genuine unavailable-context, reset, and compaction barriers.

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

Source inspection establishes the producer-to-barrier-to-fallback path; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The exception is a small fix at the shared decision owner, serves durable and memory accounting consumers, and leaves actual unknown-usage boundaries intact.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Unavailable-context barrier changes intended behavior with a stated reason (268ff00: The cited commit extracted accounting into a policy shared by durable and memory backends; it carries the barrier forward and does not establish its original introduction.)
  • Gateway abort partial usage keeps the original intent (fix(ai): mark interrupted stream usage as unavailable #120008: Interrupted or unmeasured output must remain visibly unavailable rather than claim complete usage.)

Testing

Proof path: unit tests only.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 268ff00 adds src/config/sessions/session-transcript-accounting-policy.ts:16 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 268ff00f668a; files: src/config/sessions/session-transcript-accounting-policy.ts)

PR surface

Source +18, Tests +76. Total +94 across 2 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 1 19 1 +18
Tests 1 76 0 +76
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 95 1 +94

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The reported post-abort delays have a concrete source mechanism, with limited impact on sessions that lose their usage anchor.
  • 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.

Rank-up moves

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

  • Attach redacted after-fix Gateway output for the stop-and-next-prompt scenario.

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.

Reviewed October 19, 2026, 1:45 AM ET / 05:45 UTC.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 26, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

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

Labels

P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant