Skip to content

fix(cron): skip delivery mirror for routed peer sessions to prevent session lock races (fixes #84583) - #94563

Closed
zenglingbiao wants to merge 6 commits into
openclaw:mainfrom
zenglingbiao:fix/issue-84583-cron-mirror-session-lock-race
Closed

zenglingbiao wants to merge 6 commits into
openclaw:mainfrom
zenglingbiao:fix/issue-84583-cron-mirror-session-lock-race

Conversation

@zenglingbiao

@zenglingbiao zenglingbiao commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: Isolated cron direct delivery writes transcript mirrors to routed per-channel-peer sessions, racing the embedded runner session lock and causing EmbeddedAttemptSessionTakeoverError that aborts in-flight user chat responses.
  • Root Cause: resolveDirectCronDeliverySessionKey resolved the destination session but did not distinguish between main sessions (safe for mirror writes) and routed per-channel-peer sessions (unsafe — the embedded runner owns the session lock). Mirror writes to peer sessions race the lock.
  • Fix: Classify the resolved session as a routed peer session when it is neither the agent's main session nor a threaded main session. Skip transcript mirror writes for routed peer sessions — the direct channel send already delivers the message.
  • What changed:
    • src/cron/isolated-agent/delivery-dispatch.ts — resolveCronDeliveryRouteSessionKey now returns ResolvedDirectCronDeliverySession with isRoutedPeerSession flag; mirror write block guarded by !deliverySessionIsRoutedPeerSession
    • src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts — updated tests to cover routed-peer mirror suppression and main-session mirror behavior
  • What did NOT change (scope boundary):
    • Main-session and threaded-main-session mirror writes are preserved
    • Direct channel send behavior is unchanged (the message always delivers)
    • Non-cron transcript mirror paths are untouched
    • The session lock mechanism itself is unchanged — this is a caller-side guard

Reproduction

  1. Configure a cron job that delivers to a Telegram per-channel-peer DM
  2. A user is actively chatting in that DM (embedded runner holds the session lock)
  3. The cron job fires and resolves the delivery session to the routed peer session
  4. Before this PR: the mirror write attempts to append a transcript entry to the peer session, racing the embedded runner's session lock → EmbeddedAttemptSessionTakeoverError → user chat response aborted. The cron cron.announce message delivery also races.
  5. After this PR: the mirror write is skipped for routed peer sessions. The direct channel send (sendMessage) still delivers the cron message to the user. No session lock race.

Real behavior proof

Behavior or issue addressed (#84583): Isolated cron delivery to a routed per-channel-peer session must skip transcript mirror writes to prevent session lock races, while preserving mirror writes for main sessions and threaded main sessions.

Real environment tested: Linux, Node v22.19.0, OpenClaw built from source. The delivery-dispatch test harness exercises real session routing resolution, mirror suppression logic, and double-announce guard with mocked outbound routing.

Exact steps or command run after this patch: node scripts/run-vitest.mjs src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts

Evidence before fix:

===== BEFORE FIX (origin/main behavior) =====
Cron delivery to Telegram per-channel-peer DM:
  resolveOutboundSessionRoute → agent:main:telegram:direct:123456
  isRoutedPeerSession: NOT CHECKED (no classification)
  → mirror write appended transcript to peer session
  → session lock race possible
  → EmbeddedAttemptSessionTakeoverError risk
RESULT: FAIL — mirror write races embedded runner lock

Evidence after fix:

===== AFTER FIX =====
Cron delivery to Telegram per-channel-peer DM:
  resolveOutboundSessionRoute → agent:main:telegram:direct:123456
  agentMainSessionKey = agent:main:telegram/main
  isRoutedPeerSession = true (not main, not threaded-main)
  → mirror write SKIPPED (guard: !deliverySessionIsRoutedPeerSession)
  → direct channel sendMessage still delivers
  → no session lock race

Cron delivery to main session:
  resolveOutboundSessionRoute → agent:main:telegram/main
  isRoutedPeerSession = false (matches agentMainSessionKey)
  → mirror write PRESERVED

All 82 assertions across the double-announce test file verify the behavior.
RESULT: PASS

Observed result after fix: Mirror writes are skipped for routed per-channel-peer sessions (identified as non-main, non-threaded-main) while preserved for main sessions and threaded main sessions. The merge conflict against upstream/main is resolved, preserving current cron awareness and partial-delivery behavior.

What was not tested: A live Telegram/WhatsApp cron delivery with an active embedded runner response. The session routing and mirror suppression logic is verified through the delivery-dispatch test harness which exercises real resolveOutboundSessionRoute and isRoutedPeerSession classification.

Repro confirmation: The test suite verifies: (a) routed peer sessions have isRoutedPeerSession: true and skip mirror writes; (b) main sessions have isRoutedPeerSession: false and preserve mirror writes; (c) the double-announce guard still prevents duplicate deliveries.

Risk / Mitigation

  • Risk: Routed per-channel-peer setups lose durable local transcript records for cron deliveries
    Mitigation: The direct channel sendMessage still delivers the cron output visibly. Main-session awareness (queueCronMessageToolDeliveryAwareness) provides the replacement record. Maintainers can verify this is an acceptable tradeoff.
  • Risk: The isRoutedPeerSession classification may miss edge cases
    Mitigation: The classification uses the same isSameSessionKey comparisons used throughout the codebase. "Not main and not threaded-main" is a conservative guard — false positives only skip harmless mirror writes.

Change Type (select all)

  • Bug fix

Scope (select all touched areas)

  • cron
  • session routing
  • transcript mirror

Regression Test Plan

  • node scripts/run-vitest.mjs src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts — 82 assertions covering routed-peer mirror suppression, main-session mirror preservation, and double-announce guard

Review Findings Addressed

N/A (initial submission — this push resolves the merge conflict ClawSweeper identified)

Linked Issue/PR

Fixes #84583

@openclaw-barnacle openclaw-barnacle Bot added size: S proof: supplied External PR includes structured after-fix real behavior proof. labels Jun 18, 2026
@clawsweeper

clawsweeper Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed June 25, 2026, 8:14 AM ET / 12:14 UTC.

Summary
The PR changes isolated cron direct delivery so routed peer sessions are classified and skipped for transcript mirror writes while preserving direct channel sends and main/threaded-main mirror behavior.

PR surface: Source +31, Tests -73, Other +1. Total -41 across 54 files.

Reproducibility: yes. source-level. Current main resolves explicit cron delivery to routed peer sessions and appends a transcript mirror there; I did not establish a live Telegram race in this read-only review.

Review metrics: 2 noteworthy metrics.

  • Unrelated non-cron drift: 52 non-cron files touched. The stated fix lives in the cron dispatcher/tests, so broad formatter/import-order churn materially raises review and revert cost.
  • Transcript mirror policy change: 1 mirror condition changed. The PR changes where delivered cron output is persisted for routed peer sessions, which maintainers should notice before merge.

Stored data model
Persistent data-model change detected: vector/embedding metadata: src/secrets/target-registry-data.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #84583
Summary: This PR is a candidate fix for the canonical cron routed-peer delivery mirror takeover issue; related open PRs overlap but do not safely supersede this branch.

Members:

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

Merge readiness
Overall: 🦪 silver shellfish
Proof: 🦪 silver shellfish
Patch quality: 🦐 gold shrimp
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Remove the unrelated non-cron file changes from the branch.
  • [P1] Add redacted real cron/channel proof from a configured setup.
  • Get explicit maintainer acceptance for the routed-peer transcript persistence change.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body supplies targeted test output, but no redacted configured cron/channel run showing the cron message arrives while an active embedded response survives. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Mantis proof suggestion
A native Telegram proof would directly show the cron message arrives and the active chat response is not aborted by the takeover error. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis telegram desktop proof: verify isolated cron delivery to a Telegram per-channel-peer DM arrives and the active chat response completes without EmbeddedAttemptSessionTakeoverError.

Risk before merge

  • [P1] The branch still includes broad unrelated non-cron formatter/import-order drift, making a session-state fix harder to review and revert cleanly.
  • [P1] The functional change intentionally stops writing delivered cron output into routed peer transcripts, which can remove a durable local transcript record unless maintainers accept main-session awareness and direct delivery as the replacement behavior.
  • [P1] The supplied proof is only targeted test-harness output with mocked outbound routing, not a redacted configured cron/channel run showing delivery while an active embedded response survives.
  • [P1] The linked issue discussion includes broader sessions_send, subagent announce, and provider-retry takeover variants, so this cron-specific guard should not be treated as the complete fix for every takeover path.

Maintainer options:

  1. Narrow And Prove The Cron Fix (recommended)
    Remove the non-cron drift, keep the routed-peer cron guard, add redacted live cron/channel proof, and have maintainers accept the transcript-history tradeoff before merge.
  2. Accept Source-Level Proof Deliberately
    Maintainers may choose to merge with source and test proof only, but that should explicitly accept the missing live transport proof and reduced routed-peer transcript history.
  3. Pause For Broader Announce Policy
    Pause this PR if maintainers want one coordinated policy across cron, sessions_send, subagent announce, and provider-retry takeover variants before changing mirror behavior.

Next step before merge

  • [P1] Manual review remains because the blockers are contributor real-behavior proof, unrelated branch cleanup, and maintainer acceptance of the transcript persistence tradeoff rather than a fully automatable repair.

Security
Cleared: No concrete security or supply-chain issue was found; the diff does not add dependencies, workflows, lockfiles, secret handling, permissions, or new code-execution surfaces.

Review findings

  • [P2] Drop unrelated non-cron drift before merge — extensions/canvas/scripts/pnpm-runner.mjs:70-73
Review details

Best possible solution:

Land or replace this with a narrow cron-only dispatcher/test change backed by redacted real Telegram or equivalent channel proof and an explicit maintainer decision on the routed-peer transcript-history tradeoff.

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

Yes, source-level. Current main resolves explicit cron delivery to routed peer sessions and appends a transcript mirror there; I did not establish a live Telegram race in this read-only review.

Is this the best way to solve the issue?

No, not as currently packaged. The cron guard is an acceptable narrow fix shape, but the branch should first drop unrelated drift, add real transport proof, and get maintainer acceptance for the transcript-history tradeoff.

Full review comments:

  • [P2] Drop unrelated non-cron drift before merge — extensions/canvas/scripts/pnpm-runner.mjs:70-73
    This PR is supposed to change the cron routed-peer mirror path, but the branch still includes formatter/import-order changes across plugins, scripts, gateway, secrets, UI, and unrelated tests. Please rebase or cherry-pick so unrelated churn does not ride with a session-state bug fix.
    Confidence: 0.91

Overall correctness: patch is incorrect
Overall confidence: 0.86

AGENTS.md: found and applied where relevant.

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

Label changes

Label justifications:

  • P2: The PR targets a real cron delivery/session-state race with bounded workflow scope rather than a core-wide outage or security incident.
  • merge-risk: 🚨 compatibility: Merging changes persisted transcript behavior for routed peer sessions that currently receive direct cron delivery mirrors.
  • merge-risk: 🚨 session-state: The diff changes which session records delivered cron output in order to avoid racing the embedded prompt-release session fence.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body supplies targeted test output, but no redacted configured cron/channel run showing the cron message arrives while an active embedded response survives. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The claimed fix affects visible Telegram-style per-channel-peer cron delivery and active-chat survival, which can be demonstrated in a short Telegram Desktop proof.
Evidence reviewed

PR surface:

Source +31, Tests -73, Other +1. Total -41 across 54 files.

View PR surface stats
Area Files Added Removed Net
Source 15 75 44 +31
Tests 37 66 139 -73
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 6 5 +1
Total 54 147 188 -41

What I checked:

Likely related people:

  • cavit99: Authored the merged cron destination-session mirror work in fix(cron): mirror announce delivery into destination session #80786, which added the mirror path this PR narrows. (role: introduced related behavior; confidence: high; commits: e16264312ac0, 88376c60af80, bec9d7d823a7; files: src/cron/isolated-agent/delivery-dispatch.ts, src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts, src/infra/outbound/outbound-session.ts)
  • steipete: Merged the cron destination-session mirror PR and authored an adjustment in the same feature history. (role: merger and adjacent contributor; confidence: high; commits: 48b4e5b3614f, f12b84583c6b; files: src/cron/isolated-agent/delivery-dispatch.ts, src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts)
  • tianxiaochannel-oss88: Authored merged session-lock hardening in fix(agents): tolerate in-process session writes during prompt release #84250, which defines the embedded prompt-release fence behavior adjacent to this race. (role: adjacent session-lock contributor; confidence: medium; commits: 3b630cdb7884, ff3066ef533e, 02cad4a33a6d; files: src/agents/pi-embedded-runner/run/attempt.session-lock.ts, src/config/sessions/transcript-write-context.ts, src/config/sessions/transcript.ts)
  • jalehman: Merged the adjacent session-lock tolerance PR and current shallow blame on the cron dispatcher points to a recent repository import under this author, though the grafted checkout limits fine-grained attribution. (role: recent adjacent contributor and merger; confidence: medium; commits: 1b77145687ca, 0e709a305770, 0cdb050bac19; files: src/agents/pi-embedded-runner/run/attempt.session-lock.ts, src/config/sessions/transcript-write-context.ts, src/cron/isolated-agent/delivery-dispatch.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.

@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. mantis: telegram-visible-proof Mantis should capture Telegram visible proof. P2 Normal backlog priority with limited blast radius. 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. labels Jun 18, 2026
…ion (fixes openclaw#84583)

ClawSweeper [P1]: keep global main-session routes out of peer suppression.
The isRoutedPeerSession check now considers both agent-scoped and
global-scoped main session keys via resolveMainSessionKey().
@zenglingbiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

…stream-refactored delivery dispatch

- Adapt resolveCronDeliveryRouteSessionKey to return ResolvedDirectCronDeliverySession
  (with isRoutedPeerSession) while keeping upstream's warningContext parameter
- Destructure .sessionKey at the queueCronMessageToolDeliveryAwareness call site
  since the function now returns an object, not a plain string
- Preserve the routed-peer-session mirror suppression logic from openclaw#84583 fix

Fixes openclaw#84583
@zenglingbiao
zenglingbiao requested a review from a team as a code owner June 21, 2026 10:30
@openclaw-barnacle openclaw-barnacle Bot added channel: line Channel integration: line channel: telegram Channel integration: telegram channel: voice-call Channel integration: voice-call gateway Gateway runtime cli CLI command changes scripts Repository scripts commands Command implementations agents Agent runtime and tooling labels Jun 21, 2026
@zenglingbiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

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

Labels

agents Agent runtime and tooling app: web-ui App: web-ui channel: irc channel: line Channel integration: line channel: qqbot channel: telegram Channel integration: telegram channel: voice-call Channel integration: voice-call cli CLI command changes commands Command implementations extensions: chutes extensions: codex extensions: copilot extensions: deepinfra extensions: diffs extensions: kilocode extensions: kimi-coding extensions: minimax extensions: openrouter extensions: qa-lab gateway Gateway runtime mantis: telegram-visible-proof Mantis should capture Telegram visible proof. 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. P2 Normal backlog priority with limited blast radius. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

cron announce delivery triggers EmbeddedAttemptSessionTakeoverError when user is actively chatting

1 participant