Skip to content

fix: deferred post-turn compaction fails after a reply completes - #159353

Merged
obviyus merged 7 commits into
openclaw:mainfrom
ethanhawkes-gif:runt/fix-post-turn-compaction-authority
Oct 17, 2026
Merged

obviyus merged 7 commits into
openclaw:mainfrom
ethanhawkes-gif:runt/fix-post-turn-compaction-authority

Conversation

@ethanhawkes-gif

@ethanhawkes-gif ethanhawkes-gif commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Related: #158070, #171668

What Problem This Solves

Fixes automatic post-turn compaction failing after a target session replies to sessions_send with timeoutSeconds: 0 and the source turn has already completed.

User Impact

Delegated target sessions compact after delivery instead of retaining an overfull context. No configuration, stored-row schema, or protocol changes are introduced.

Why This Change Was Made

Extends @ethanhawkes-gif's fix at the existing session-maintenance owner rather than retaining a separate scheduling wrapper. The owner drops the launching turn's Gateway caller and operator-tool scopes, using the same isolation primitives as #171668. Both direct-chat and delegated maintenance then use the target's existing maintenance ownership, lifecycle checks, writer admission, session revision checks, cancellation, and pre-effect authorization. No source grants are copied or new ambient grants created.

The original 597-line integration fixture is replaced with focused tests in the existing owner/admission suites. Its old negative fixture supplied an empty Gateway context, which made every case fail the Gateway fence irrespective of the intended invalidation; the replacement includes a functioning Gateway resolver and a matched successful control. The complete delta against merged main is production +9/-2 and tests +151/-3 across three files.

Evidence

Frozen main: 25933024a1e197fa1a503e84b573a47203fc674f.
Current head: 4fd16c989c99be3d10aefaf81965df8a6cc89482. Runtime proof and focused tests: 459b3ce72bc2b2c8f4939efe39c260af13164916. The initial merge used main 51ea9e50ecb; the later CI-repair merge includes main 4513e9e09633a740f58b4ccf8802597968868c47. Targeted diffs show the maintenance owner, scheduler, and reply-maintenance adapter are byte-for-byte unchanged from the E2E head. Tests are unchanged from 60c83362dbc, which only removed an unused excess sessionId property from a test's SessionAccessScope.

Cell Observed on frozen main Candidate
Real source chat → sessions_send(timeoutSeconds: 0) → target reply, repeat 1 Both replies delivered; optional maintenance failed with agent tool caller authority is no longer active; zero compaction provider calls Both replies delivered; two compaction provider calls; durable compactionCount 1; tokens 125000 → 62206
Same delegated flow, repeat 2 Same failure; target retained 125000 tokens and compactionCount 0; health passed Same successful compaction; durable compactionCount 1; tokens 125000 → 62206; health passed
Direct-chat control, two repeats Both compacted; compactionCount 1, tokens 60050 → 43996, two compaction provider calls each Both compacted; compactionCount 1, tokens 60050 → 44113; two compaction provider calls each; health passed
Manual sessions.compact control Succeeded; tokens 125050 → 6664, compactionCount 1 Reports Already compacted, since automatic maintenance already succeeded

Observed security cells through a real isolated Gateway, loopback provider, and diagnostic plugin:

Boundary Observed result
Source tool grants Actual source cron.list succeeds. The identical call from target maintenance fails with trusted agent runtime identity required for this gateway call; target compaction still succeeds with two provider calls and one durable compaction.
Target reset before maintenance Reset completes before releasing the held target response. Zero maintenance provider calls; zero new compaction entries/windows/count.
Target deletion before maintenance After the endpoint's explicit changed-owner refusal, one fresh deletion request succeeds with deleted: true. Target row absent; zero maintenance provider calls or compaction persistence.
Foreground preemption Foreground arrival cancels held maintenance. Before allowing the successor to proceed, SQLite still has compactionCount 0 and no compaction entries/windows; stale summary is never persisted. The foreground reply then completes, and its fresh maintenance may compact normally.

Lifecycle-generation and Gateway-instance retirement are separately covered before admission and after awaited flush in the focused admission tests. Failed/aborted foreground settlement and actual cancellation cleanup retain their existing owner tests. No invalidation case relies solely on a matching session ID.

Install/build succeeded once. Formatting and focused lint passed. Owner tests: 19 passed, 11.64 s one-file wall time (Vitest 6.62 s). Admission/authority-loss tests: 8 passed, 91.46 s wall time (Vitest 81.50 s, including 48 s cold worker preparation). Existing scheduler test: 1 passed, 63.30 s wall time. Initial copied-install dependency failures were resolved by the install. The identical delegated/direct baseline harnesses changed only the candidate path, evidence destination, and recorded SHA. The negative fixture's first startup attempt matched the wrong readiness log text; the Gateway had become ready, and correcting the event match did not change any timeout or product behavior.

Hosted CI on 459b3ce found the test-only excess-property error fixed by 60c83362dbc, plus an inherited checks-fast-baseline-ratchets mock-exports error. Main fixed that ratchet in #174947; this head includes that repair through the main merge, without an independent fixture workaround. Exact-head CI is green. ClawSweeper's exact-head review is ready, with no findings or remaining proof blockers. No merge has been performed.

Merge danger: two-way door; reverting restores the previous ownership behavior without a migration. The security-boundary blast radius is optional session maintenance across direct and delegated agent turns. An incorrect scope transition could deny valid maintenance or retain source privileges; the allowed/revoked final-effect cells above protect that boundary.

@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Sep 27, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. 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 27, 2026
@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR removes inherited foreground caller and operator authority before session maintenance executes.

Example: A target session replies to sessions_send with timeoutSeconds: 0 after the source turn completes.

  • Before: Automatic compaction fails with expired caller authority, retaining 125000 tokens.
  • After: Recorded candidate runs complete compaction, reducing tokens to 62206 with compactionCount 1.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused root-cause repair with recorded shipped-entry-point behavior and authority-boundary controls; outstanding infrastructure checks remain landing gates.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded isolated-Gateway runs exercise real source chat through sessions_send, target delivery and durable compaction, with repeated successful candidate results and direct-chat controls. Nearest-forbidden source cron grants are rejected, reset/deletion prevent maintenance effects, and foreground preemption prevents stale persistence; focused tests additionally cover Gateway retirement before admission and after flushing. Production comparisons carry this evidence to the reviewed head.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Delegated sessions retain overfull context because automatic post-reply compaction inherits an already completed source turn's authority.
Reason: The repair restores independently owned maintenance using existing isolation primitives and adds no configuration, public API or stored format.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current maintenance failure at the existing owner without introducing a competing path; no actionable patch defects were found.

Priority: P2
Reviewed head: 4fd16c989c99be3d10aefaf81965df8a6cc89482

Before merge

None.

Findings

None.

Agent review details

How this fits together

Reply completion schedules optional maintenance, which acquires target-session admission before memory flushing and transcript compaction.

flowchart TD
  A[Completed reply] --> B[Maintenance scheduler]
  B --> C[Session maintenance owner]
  C --> D[Exit source authority scopes]
  D --> E[Target session admission]
  E --> F[Memory flush and compaction]
  F --> G[Authorized transcript persistence]
Loading

Technical review

Best possible solution:

Land the existing owner-level scope isolation once required checks complete successfully.

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

Current-main source preserves the stale asynchronous authority path, and supplied frozen-main Gateway runs record its failure; no target code was executed during this review.

Is this the best way to solve the issue?

Exiting both inherited scopes at the shared maintenance owner fixes the cause while preserving target-owned admission, ordering, cancellation and effect authorization.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Maintenance execution context keeps the original intent (60adac1: Run optional maintenance after delivery under independent ownership while preserving nested-owner ordering and actual writer settlement.)
  • Worker-backed admission coverage keeps the original intent (4bd8ee5: Move session-authority reads to workers while preserving fresh authority and lifecycle settlement.)
  • Admission fixture mock lifecycle keeps the original intent (1d76f57: Preserve database-source replacement coverage; resetting mock implementations isolates the new held-flush scenarios.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduced change: The production change exits both existing authority scopes inside the shared maintenance owner; the remaining changes cover scope isolation and admission invalidation. (src/agents/session-maintenance/coordinator.ts:148, 4fd16c989c99)
  • Current main remains affected: Fetched main executes the maintenance callback in its inherited asynchronous context without exiting either source authority scope. (src/agents/session-maintenance/coordinator.ts:147, 9dd47e67ded4)
  • Target authority remains enforced: The scheduler retains Gateway-instance, lifecycle, database-source, session-revision and cancellation checks, rechecks after flushing, and passes live authorization into compaction. (src/agents/session-maintenance/run.ts:308, 4fd16c989c99)
  • Observed Gateway results: The full PR body records repeated frozen-main failures and successful candidate delegated compaction, direct-chat controls, rejected source cron grants, no maintenance effects after reset/deletion, and foreground cancellation before stale persistence; collaborator obviyus confirms these scenarios in the re-review request. (459b3ce72bc2)
  • Proof carries to reviewed head: Targeted comparisons show no changes from the exercised production head in the coordinator, maintenance runner or reply-maintenance adapter; the added tests are unchanged from the subsequent test-type repair. (src/agents/session-maintenance/coordinator.ts:148, 4fd16c989c99)
  • Feature history: Scoped history identifies Peter Steinberger's sustained work on maintenance coordination, worker admission and lifecycle settlement; the changed execution line is attributed to the original independently owned maintenance work. (src/agents/session-maintenance/coordinator.ts:147, 60adac1aff6f)

PR surface

Source +7, Tests +148. Total +155 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 9 2 +7
Tests 2 151 3 +148
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 160 5 +155

Review metrics

Metric Value Why it matters
Production versus test delta Production +9/-2; tests +151/-3 The small owner-level repair has distinct scope-isolation and lifecycle-admission coverage.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Deferred compaction fails after delegated replies complete, while delivered replies remain intact.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 (5 earlier review cycles)
  • reviewed 2026-09-27T02:58:01.001Z sha 12e56a41b0c779a3cafb59ea82f27db18cbe2f49 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-27T17:27:44.941Z sha 85734cd26a4854fd3f40a964cf22d33cbbea5e93 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-27T23:19:31.103Z sha 85734cd26a4854fd3f40a964cf22d33cbbea5e93 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-27T23:54:43.558Z sha c378f93 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-17T02:36:04.751Z sha 4fd16c9 :: needs maintainer review before merge. :: none

Reviewed October 16, 2026, 10:45 PM ET / October 17, 2026, 02:45 UTC (Revision 6).

@openclaw-barnacle openclaw-barnacle Bot added size: L triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed size: M triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Sep 27, 2026
…fore post-turn compaction

Optional session maintenance was scheduled from within the foreground turn's
AsyncLocalStorage context, causing it to inherit the GatewayToolCallerIdentity
set by the foreground turn. When the maintenance's tool activation later called
captureGatewayToolCallerAssertion(), the captured receiptAuthority check fired
against the now-retired foreground turn and threw 'agent tool caller authority
is no longer active'.

Use withoutGatewayToolCallerIdentity() (which calls AsyncLocalStorage.exit())
to wrap the withPluginRuntimeGatewayRequestScope launch. This clears the ALS
slot before the async chain starts, so all downstream work including compaction
tool setup runs without any foreground caller authority — exactly the contract
the existing withoutGatewayToolCallerIdentity docstring describes.

captureGatewayToolCallerAssertion() and receiptAuthority remain unchanged;
legitimate revocation of active calls is fully preserved.

Tests: two new regression tests confirm (1) getGatewayToolCallerIdentity() is
undefined inside the maintenance scope when called from a stale foreground
context, and (2) captureGatewayToolCallerAssertion() returns undefined rather
than a throwing function. Both fail on the unfixed baseline.
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 12, 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. labels Oct 17, 2026
@obviyus

obviyus commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

The PR body now records observed frozen-main failures and successful candidate delegated/direct compaction, actual source-grant rejection in maintenance, zero maintenance provider/persistence effects after reset/deletion, foreground preemption, and measured focused test timing. The four earlier proof blockers are addressed. Current head 60c8336 differs from the exercised production head only by removing an excess property from a test scope. Please review this exact head; do not merge.

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

Current head is 4fd16c9 after merging the main CI repair #174947. Targeted diffs confirm the maintenance owner, scheduler, and reply-maintenance adapter are unchanged from the exercised E2E head 459b3ce; tests are unchanged from the one-property type repair 60c8336. The PR body records observed successful delegated compaction twice, direct-chat controls, source-grant denial, zero maintenance effects after reset/deletion, foreground preemption, and focused test timing. Please review this exact head; do not merge.

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 17, 2026
@obviyus
obviyus merged commit 5fbb405 into openclaw:main Oct 17, 2026
144 of 154 checks passed
@obviyus

obviyus commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator

Landed as 5fbb405.

  • Bug: After a reply reached a session via sessions_send, its post-delivery compaction inherited the source turn's retired caller authority and failed (agent tool caller authority is no longer active); the session stayed at 125k tokens.
  • Fix: The maintenance owner (createSessionMaintenanceOwner.run) drops the launching caller/operator scopes and keeps only the target session's own admission.
  • Proof: Real Gateway: delegated sessions now compact 125,000 → 62,206 tokens (2 repeats); direct-chat control unchanged; source grants are not usable by maintenance, and reset/delete/foreground-arrival cases make no provider calls or writes.

Thanks @ethanhawkes-gif for the fix.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…nclaw#159353)

Related: openclaw#158070, openclaw#171668

## What Problem This Solves

Fixes automatic post-turn compaction failing after a target session replies to `sessions_send` with `timeoutSeconds: 0` and the source turn has already completed.

## User Impact

Delegated target sessions compact after delivery instead of retaining an overfull context. No configuration, stored-row schema, or protocol changes are introduced.

## Why This Change Was Made

Extends @ethanhawkes-gif's fix at the existing session-maintenance owner rather than retaining a separate scheduling wrapper. The owner drops the launching turn's Gateway caller and operator-tool scopes, using the same isolation primitives as openclaw#171668. Both direct-chat and delegated maintenance then use the target's existing maintenance ownership, lifecycle checks, writer admission, session revision checks, cancellation, and pre-effect authorization. No source grants are copied or new ambient grants created.

The original 597-line integration fixture is replaced with focused tests in the existing owner/admission suites. Its old negative fixture supplied an empty Gateway context, which made every case fail the Gateway fence irrespective of the intended invalidation; the replacement includes a functioning Gateway resolver and a matched successful control. The complete delta against merged main is production +9/-2 and tests +151/-3 across three files.

## Evidence

Frozen main: `964a9ea2957cdb7a6566daf3d927691ad06a8557`.
Current head: `4fd16c989c99be3d10aefaf81965df8a6cc89482`. Runtime proof and focused tests: `459b3ce72bc2b2c8f4939efe39c260af13164916`. The initial merge used main `8f3292fff6a`; the later CI-repair merge includes main `01edef4f3f37deb66bf4e448ac2ff30f8b644771`. Targeted diffs show the maintenance owner, scheduler, and reply-maintenance adapter are byte-for-byte unchanged from the E2E head. Tests are unchanged from `60c83362dbc`, which only removed an unused excess `sessionId` property from a test's `SessionAccessScope`.

| Cell | Observed on frozen main | Candidate |
| --- | --- | --- |
| Real source chat → `sessions_send(timeoutSeconds: 0)` → target reply, repeat 1 | Both replies delivered; optional maintenance failed with `agent tool caller authority is no longer active`; zero compaction provider calls | Both replies delivered; two compaction provider calls; durable compactionCount 1; tokens 125000 → 62206 |
| Same delegated flow, repeat 2 | Same failure; target retained 125000 tokens and compactionCount 0; health passed | Same successful compaction; durable compactionCount 1; tokens 125000 → 62206; health passed |
| Direct-chat control, two repeats | Both compacted; compactionCount 1, tokens 60050 → 43996, two compaction provider calls each | Both compacted; compactionCount 1, tokens 60050 → 44113; two compaction provider calls each; health passed |
| Manual `sessions.compact` control | Succeeded; tokens 125050 → 6664, compactionCount 1 | Reports `Already compacted`, since automatic maintenance already succeeded |

Observed security cells through a real isolated Gateway, loopback provider, and diagnostic plugin:

| Boundary | Observed result |
| --- | --- |
| Source tool grants | Actual source `cron.list` succeeds. The identical call from target maintenance fails with `trusted agent runtime identity required for this gateway call`; target compaction still succeeds with two provider calls and one durable compaction. |
| Target reset before maintenance | Reset completes before releasing the held target response. Zero maintenance provider calls; zero new compaction entries/windows/count. |
| Target deletion before maintenance | After the endpoint's explicit changed-owner refusal, one fresh deletion request succeeds with `deleted: true`. Target row absent; zero maintenance provider calls or compaction persistence. |
| Foreground preemption | Foreground arrival cancels held maintenance. Before allowing the successor to proceed, SQLite still has compactionCount 0 and no compaction entries/windows; stale summary is never persisted. The foreground reply then completes, and its fresh maintenance may compact normally. |

Lifecycle-generation and Gateway-instance retirement are separately covered before admission and after awaited flush in the focused admission tests. Failed/aborted foreground settlement and actual cancellation cleanup retain their existing owner tests. No invalidation case relies solely on a matching session ID.

Install/build succeeded once. Formatting and focused lint passed. Owner tests: 19 passed, 11.64 s one-file wall time (Vitest 6.62 s). Admission/authority-loss tests: 8 passed, 91.46 s wall time (Vitest 81.50 s, including 48 s cold worker preparation). Existing scheduler test: 1 passed, 63.30 s wall time. Initial copied-install dependency failures were resolved by the install. The identical delegated/direct baseline harnesses changed only the candidate path, evidence destination, and recorded SHA. The negative fixture's first startup attempt matched the wrong readiness log text; the Gateway had become ready, and correcting the event match did not change any timeout or product behavior.

Hosted CI on `459b3ce` found the test-only excess-property error fixed by `60c83362dbc`, plus an inherited `checks-fast-baseline-ratchets` mock-exports error. Main fixed that ratchet in openclaw#174947; this head includes that repair through the main merge, without an independent fixture workaround. [Exact-head CI](https://github.com/openclaw/openclaw/actions/runs/38995088011) is green. [ClawSweeper's exact-head review](openclaw#159353 (comment)) is `ready`, with no findings or remaining proof blockers. No merge has been performed.

**Merge danger:** two-way door; reverting restores the previous ownership behavior without a migration. The security-boundary blast radius is optional session maintenance across direct and delegated agent turns. An incorrect scope transition could deny valid maintenance or retain source privileges; the allowed/revoked final-effect cells above protect that boundary.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S stale Marked as stale due to inactivity 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.

2 participants