Skip to content

fix(sessions): prevent lifecycle races and unsafe session management - #114477

Merged
steipete merged 3 commits into
mainfrom
codex/session-lifecycle-management-sweep
Jul 27, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/session-lifecycle-management-sweep

Conversation

@steipete-oai

@steipete-oai steipete-oai commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Closes #114187
Closes #113005
Closes #103089
Closes #103077
Related: #106641

What Problem This Solves

Fixes an issue where users creating or managing sessions could lose concurrent session records, target the wrong session generation during deletion, bypass plugin ownership during patch/fork/link/reset, or lose bundled MCP tools and per-run timeout control when spawning subagents. Visible session creation now remains on the existing controlled spawn path instead of introducing a separate route around inherited tool policy, sandboxing, depth, and concurrency limits.

Why This Change Was Made

Serialize session creation on canonical lifecycle identities, enforce one storage-neutral plugin ownership contract for create/adoption, patch, delete, and reset, and bind archive-then-delete to the exact returned session generation. Materialize inherited MCP capabilities after final tool-policy/schema projection and expose the canonical per-run timeout consistently for native, ACP, and visible subagent runs. Preserve plugin ownership across reset and when a plugin reset materializes a missing session.

User Impact

Agents can safely reset and delete visible sessions, spawn visible and background sessions through the normal capability-controlled path, retain authorized bundled MCP tools, and set bounded run timeouts. Plugin-owned sessions cannot mutate or destroy operator-owned or foreign-plugin sessions, and concurrent session creation, reset, and deletion preserve the correct session records.

Evidence

  • 547 passing exact-head tests: 531 focused lifecycle, ownership, concurrency, transcript-projection, Gateway, native/ACP, timeout, and MCP-policy regressions, plus all 16 real local/Gateway terminal end-to-end cases. Includes the previously failing cross-client sessions.send while a SQLite transcript projection is rebuilding.
  • Four passing real-Gateway QA scenarios with the OpenAI-compatible mock: subagent handoff, forked context, bounded fan-out synthesis, and runtime sessions_spawn.
  • Passing full pnpm check:changed, including core and test typechecks, all core/package/UI lint shards, SDK boundary and surface checks, SQLite/schema and database-first guards, security guards, and zero runtime import cycles.
  • Passing pnpm build, including all 142 plugin SDK exports and Control UI build/performance validation.
  • Clean Codex autoreview of the final diff and clean trufflehog secret scan.
  • Passed real OpenAI API-key live proof for immutable head 225cef8ebfa7a27428e53253468475fddda8502e: Run Native live gateway fresh OpenAI API-key default, including successful repository-secret auth/profile hydration and target-SHA verification. The four mock-provider Gateway scenarios are reported separately and are not represented as real-provider proof.
  • AI-assisted; all independent-review findings were corrected and rerun before publication.

Ownership and compatibility decision

Session ownership is authoritative: a plugin can adopt, patch, reset, delete, fork, or link only sessions owned by that same plugin. Cross-owner operations intentionally fail closed; no compatibility alias or runtime fallback is intended. Model-visible reset and delete require existing visibility, current-session refusal, archival, and exact lifecycle-generation guards. Persistent creation remains on the existing capability-controlled visible-spawn path.

Final immutable-head validation

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Jul 27, 2026
@steipete
steipete force-pushed the codex/session-lifecycle-management-sweep branch from 96907c0 to 56f7b2e Compare July 27, 2026 09:26
@clawsweeper clawsweeper Bot added 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Jul 27, 2026
@clawsweeper

clawsweeper Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 27, 2026, 6:10 AM ET / 10:10 UTC.

ClawSweeper review

What this changes

The branch serializes session lifecycle work, makes plugin ownership authoritative for session operations, refreshes subagent inheritance after final tool policy, adds a runTimeoutSeconds spawn parameter, and waits for an in-flight transcript projection rebuild before counting messages.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep this PR open for maintainer review. It is a broad, evidence-backed hardening patch with no newly supported line-level correctness defect in the supplied diff, but it intentionally changes the plugin session-ownership contract: previously permitted cross-owner patch, reset, delete, fork, link, and adoption paths now fail closed. The maintainer label and the compatibility/security boundary make that acceptance decision human-owned.

Likely related people: steipete is the recent session-lifecycle contributor shown by the branch history (low confidence; no independent current-main ownership history could be read in this sandbox).

Priority: P1
Reviewed head: 225cef8ebfa7a27428e53253468475fddda8502e
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong real-Gateway and live-provider proof plus extensive targeted regressions support the patch, while the deliberate compatibility/security contract remains for maintainer acceptance and remaining CI completion.
Proof confidence 🦞 diamond lobster (5/6) ✨ media proof bonus Sufficient (linked_artifact): The PR body and follow-up describe an exact-head real OpenAI API-key Gateway run plus real running-Gateway scenarios, and distinguish those from mock-provider scenarios; the provided context also marks the PR proof: sufficient.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (linked_artifact): The PR body and follow-up describe an exact-head real OpenAI API-key Gateway run plus real running-Gateway scenarios, and distinguish those from mock-provider scenarios; the provided context also marks the PR proof: sufficient.
Evidence reviewed 6 items PR scope and stated compatibility decision: The PR body explicitly makes plugin session ownership authoritative and says cross-owner patch, reset, delete, fork, link, and adoption requests intentionally fail closed without a runtime fallback.
Unified ownership enforcement: The proposed helper returns an INVALID_REQUEST error when a plugin runtime attempts an action on a session whose stored plugin owner differs, and the diff wires this check into patch, delete, create/fork-link, and reset paths.
Lifecycle-race coverage: The branch adds concurrent create/delete and same-key creation coverage, plus ownership and reset-race regressions, according to the test additions and PR evidence.
Findings None None.
Security None None.

How this fits together

Agent-facing sessions and sessions_spawn tools call Gateway session APIs, which authorize lifecycle operations and read or write persisted session records. The same runtime prepares the parent agent’s final authorized tool set before child sessions inherit it, so storage state, plugin boundaries, and subagent capability policy must agree.

flowchart LR
  A[Agent session tools] --> B[Gateway session APIs]
  B --> C[Ownership and visibility checks]
  C --> D[Lifecycle admission]
  D --> E[Persisted session records]
  A --> F[Subagent launch]
  F --> G[Final authorized tool policy]
  G --> H[Child agent session]
Loading

Decision needed

Question Recommendation
Should OpenClaw permanently adopt fail-closed same-plugin ownership for all existing session patch, reset, delete, fork, link, and adoption operations, accepting that cross-owner plugin callers now receive INVALID_REQUEST without a runtime compatibility path? Accept authoritative ownership: Merge with the stated fail-closed contract and rely on the new regression coverage to prevent cross-plugin session access.

Why: The implementation is mechanically coherent and the PR expressly frames this as an intentional compatibility and authorization-boundary change, but only maintainers can decide whether that breaking plugin-runtime contract is the desired product policy.

Before merge

  • Resolve merge risk (P2) - Existing in-process plugin runtimes that used cross-owner session operations will receive INVALID_REQUEST after merge; the branch intentionally has no compatibility alias or fallback, so maintainers must accept that upgrade behavior.
  • Resolve merge risk (P1) - The PR changes persisted session lifecycle ordering across creation, reset, archive, delete, and transcript projection recovery; remaining exact-head CI shards should complete successfully before landing.
  • Complete next step (P1) - A maintainer must decide whether the intentional, fail-closed plugin ownership change is the permanent compatibility contract; no narrow automated repair is indicated by the current review.
Agent review details

Security

None.

PR surface

Source +256, Tests +848, Docs +8. Total +1112 across 32 files.

View PR surface stats
Area Files Added Removed Net
Source 17 320 64 +256
Tests 13 882 34 +848
Docs 2 12 4 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 32 1214 102 +1112

Review metrics

Metric Value Why it matters
Model-facing session controls 2 actions added, 1 timeout parameter added The sessions tool gains reset/delete and sessions_spawn gains runTimeoutSeconds, expanding model-visible control over persisted sessions and child-run duration.
Ownership-protected operations 6 operation classes guarded Patch, reset, delete, fork, link, and adoption now use the same plugin ownership invariant, so the contract needs explicit maintainer acceptance.

Stored data model

Persistent data-model change detected: serialized state: src/agents/tools/sessions-spawn-tool.test.ts, serialized state: src/agents/tools/sessions-spawn-tool.ts, serialized state: src/agents/tools/sessions-spawn-visible.ts, serialized state: src/agents/tools/sessions-tool.test.ts, serialized state: src/agents/tools/sessions-tool.ts, serialized state: src/config/sessions/session-accessor.sqlite-active-events.ts, and 15 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: canonical
Canonical: #114477
Summary: This PR is the shared candidate fix for four explicitly linked session defects; the Slack HTTP scope report is only adjacent because this branch does not show a corresponding route-scope repair.

Members:

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

Merge-risk options

Maintainer options:

  1. Accept the fail-closed ownership contract (recommended)
    Confirm that existing plugin runtimes must only operate on sessions they own, then merge after the exact-head checks complete.
  2. Add an explicit transition plan
    Pause merge until maintainers choose and document a narrowly bounded migration or plugin API strategy for any supported cross-owner integrations.

Technical review

Best possible solution:

Land only after a responsible owner explicitly accepts authoritative same-plugin ownership as the permanent plugin-runtime contract and the remaining exact-head checks finish green; retain the focused ownership, lifecycle-generation, and concurrent-operation coverage as the regression boundary.

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

Yes, at source level: the supplied related reports provide concrete direct-Gateway reproduction paths for cross-owner patch and fork access, missing inherited MCP tools under restrictive policy, and absent per-call subagent timeouts. I could not independently execute those paths because the read-only command sandbox rejected repository commands before they ran.

Is this the best way to solve the issue?

Unclear: the shared ownership and lifecycle approach is a maintainable consolidation, and the PR avoids a parallel session-create route, but accepting unconditional fail-closed behavior for existing plugin callers is a maintainer policy choice rather than a purely technical conclusion.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P1: The patch addresses session lifecycle races, plugin isolation, and subagent capability loss that can disrupt active agent workflows.
  • merge-risk: 🚨 compatibility: The branch deliberately replaces formerly permissive cross-owner plugin session operations with fail-closed errors.
  • merge-risk: 🚨 session-state: Creation, reset, archive/delete sequencing, and transcript projection recovery all change persisted session behavior.
  • merge-risk: 🚨 security-boundary: The shared ownership helper blocks a plugin runtime from accessing session rows owned by another plugin or the operator.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): The PR body and follow-up describe an exact-head real OpenAI API-key Gateway run plus real running-Gateway scenarios, and distinguish those from mock-provider scenarios; the provided context also marks the PR proof: sufficient.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body and follow-up describe an exact-head real OpenAI API-key Gateway run plus real running-Gateway scenarios, and distinguish those from mock-provider scenarios; the provided context also marks the PR proof: sufficient.

Evidence

What I checked:

  • PR scope and stated compatibility decision: The PR body explicitly makes plugin session ownership authoritative and says cross-owner patch, reset, delete, fork, link, and adoption requests intentionally fail closed without a runtime fallback. (src/gateway/session-plugin-ownership.ts:12, 56f7b2e1be4e)
  • Unified ownership enforcement: The proposed helper returns an INVALID_REQUEST error when a plugin runtime attempts an action on a session whose stored plugin owner differs, and the diff wires this check into patch, delete, create/fork-link, and reset paths. (src/gateway/session-plugin-ownership.ts:12, 56f7b2e1be4e)
  • Lifecycle-race coverage: The branch adds concurrent create/delete and same-key creation coverage, plus ownership and reset-race regressions, according to the test additions and PR evidence. (src/gateway/server.sessions.create.test.ts:65, 56f7b2e1be4e)
  • Final-policy inheritance design: The branch keeps a mutable inherited allowlist reference and refreshes it after MCP/LSP materialization, final policy, and schema projection, addressing the reported loss of authorized bundle MCP tools in children. (src/agents/embedded-agent-runner/run/attempt-bundle-tools.ts:201, 56f7b2e1be4e)
  • Current CI and proof context: The provided GitHub context reports the exact-head prompt snapshot check as successful, many focused and live-provider checks successful, and some compact test shards still in progress; the PR also has the proof: sufficient label after a real OpenAI Gateway run. (225cef8ebfa7)
  • Repository-policy review constraint: The supplied root AGENTS.md treats plugin APIs, session state, setup/fallback behavior, and fail-closed changes as compatibility-sensitive, requiring maintainer-visible treatment even with green CI. (AGENTS.md:1, b8e7f27ff254)

Likely related people:

  • steipete: The provided branch history attributes all three implementation commits, including the lifecycle hardening and transcript projection follow-up, to this contributor. Independent current-main provenance could not be inspected because the read-only command sandbox failed before repository commands ran. (role: recent session-lifecycle contributor; confidence: low; commits: 56f7b2e1be4e, bef7b1059162, 225cef8ebfa7; files: src/gateway/session-create-service.ts, src/gateway/session-reset-service.ts, src/gateway/session-plugin-ownership.ts)

Rank-up moves

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

  • Obtain explicit maintainer acceptance of the fail-closed same-plugin ownership contract.
  • Wait for the remaining exact-head compact CI shards to finish successfully before merge.

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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-07-27T09:32:24.355Z sha 56f7b2e :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-27T09:46:53.681Z sha 56f7b2e :: needs maintainer review before merge. :: none
  • reviewed 2026-07-27T09:56:04.179Z sha bef7b10 :: needs maintainer review before merge. :: none

Copy link
Copy Markdown
Contributor Author

Validation update for reviewed head 56f7b2e1be4e3638bb146f92c4cb309cdc2d17c5:

  • Real OpenAI API-key Gateway proof: passed, including Hydrate live auth/profile inputs and Run Native live gateway fresh OpenAI API-key default in the exact-head live-provider run. The selected immutable SHA and live suite filter also both passed verification.
  • Fresh isolated Linux Testbox: 493/493 focused tests passed, covering 16 concurrent creates on the same key, concurrent create/delete, reset and replacement-generation races, authorized and cross-owner plugin adoption/patch/reset/delete/fork/link, visible-session visibility and self-deletion guards, native/ACP/visible runTimeoutSeconds, and authorized-versus-denied MCP/LSP inheritance under restrictive policies.
  • Actual running-Gateway QA: all four subagent-handoff, subagent-forked-context, subagent-fanout-synthesis, and runtime-tool-sessions-spawn scenarios passed. These four scenarios deliberately use the OpenAI-compatible mock and are reported separately from the real OpenAI API-key run above.
  • Independent autoreview and current ClawSweeper: no actionable code findings.

Security/compatibility decision: session ownership is authoritative. Plugins may mutate, adopt, reset, delete, fork, or link only their own sessions; cross-owner requests intentionally fail closed. Model-facing reset/delete must obey visibility and lifecycle-generation guards, and persistent creation remains on the existing authorized visible-spawn path. No runtime compatibility fallback for cross-owner mutation is intended.

Remaining landing gate: reproduce and repair the Linux check-prompt-snapshots failure before merge; the real OpenAI provider run is already green.

@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: 🦪 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 Jul 27, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 27, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

Final immutable-head proof for 225cef8ebfa7a27428e53253468475fddda8502e:

  • Full hosted CI: passed, including the formerly failing check-prompt-snapshots and checks-node-compact-small-2.
  • Real repository-secret-backed OpenAI Gateway run: passed, including fresh OPENAI_API_KEY profile hydration and the native default-provider Gateway test.
  • Fresh Linux Testbox: 531/531 focused tests plus 16/16 real Gateway/local terminal end-to-end scenarios, including owner-authorized and cross-owner operations, same-key concurrency, destructive-session generation guards, native/ACP/visible child timeouts, permitted-versus-denied MCP inheritance, and the real cross-client sessions.send transcript-rebuild regression.
  • All seven generated Codex prompt snapshots verify cleanly on Linux. Upstream behavior was inspected directly at Codex commit 95637f7056835fea66bdd0044414af480fc0fd74: codex-rs/protocol/src/dynamic_tools.rs:13, codex-rs/app-server-protocol/src/protocol/v2/thread.rs:127, codex-rs/core/src/tools/router.rs:43, and codex-rs/app-server/tests/suite/v2/dynamic_tools.rs:58.
  • Four running-Gateway mock-provider scenarios are recorded separately and are not counted as real-provider proof.

Maintainer-requested policy decision: plugin session ownership is a fail-closed security boundary; cross-owner adopt, patch, reset, delete, fork, and link are intentionally denied. The final race fix waits only for the already-scheduled canonical SQLite projection rebuild and does not introduce a file fallback or schema migration.

@steipete
steipete merged commit 9f5ba09 into main Jul 27, 2026
174 of 176 checks passed
@steipete
steipete deleted the codex/session-lifecycle-management-sweep branch July 27, 2026 10:17
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 28, 2026
…penclaw#114477)

* fix(sessions): harden lifecycle, ownership, and subagent spawning

* test(agents): refresh session tool prompt snapshots

* fix(sessions): await rebuilding transcript projections

---------

Co-authored-by: Peter Steinberger <[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 docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

2 participants