Skip to content

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

Closed
NianJiuZst wants to merge 2 commits into
openclaw:mainfrom
NianJiuZst:codex/fix-84583-cron-session-race
Closed

NianJiuZst wants to merge 2 commits into
openclaw:mainfrom
NianJiuZst:codex/fix-84583-cron-session-race

Conversation

@NianJiuZst

@NianJiuZst NianJiuZst commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #84583: cron delivery mirror appending to a routed per-channel-peer session could race the embedded runner session lock, triggering EmbeddedAttemptSessionTakeoverError and aborting the user's in-flight chat response.

resolveDirectCronDeliverySessionKey now returns the resolved outbound route alongside the session key, so the dispatch path can distinguish per-channel-peer sessions from threaded main-session variants. Delivery mirror is skipped for routed peer sessions (channel-mapped, non-main) while awareness still reaches the main session queue; the direct channel send is unaffected.

Changes

  • src/cron/isolated-agent/delivery-dispatch.ts:
    • resolveDirectCronDeliverySessionKey returns { sessionKey, route: OutboundSessionRoute | null } instead of string, exposing whether the session was resolved through outbound routing
    • New guard deliverySessionIsRoutedPeerSession checks: is this a routed session that is not the main session AND not a threaded main-session variant? Uses parseThreadSessionSuffix to correctly distinguish per-channel-peer sessions from threaded main sessions
    • Mirror condition extended with !deliverySessionIsRoutedPeerSession
  • src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts:
    • "mirrors the effective outbound payload after send hooks rewrite delivery text": updated to use main session key and assert mirror is suppressed via awareness
    • "mirrors isolated cron direct delivery into the resolved destination channel session" → renamed to "skips transcript mirror for routed channel sessions to prevent session lock races", asserts mirror NOT called and awareness queued to main session
    • "keeps successful direct delivery delivered when the transcript mirror append fails": updated to use a main-session media-only case where mirror is still attempted

Real behavior proof

Behavior addressed: Cron jobs with explicit delivery targets and session.dmScope="per-channel-peer" that resolve to a channel peer session (agent:<agent>:<channel>:direct:<peer>) trigger a session takeover error when the embedded runner has that same session active, because the direct transcript mirror mutates the session file between the prompt lock release and re-acquire.

Real environment tested: macOS Darwin 25.4.0 (arm64), Node.js v24.14.1, OpenClaw main branch

Exact steps or command run after this patch:

node scripts/run-vitest.mjs src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts
node scripts/run-vitest.mjs src/agents/pi-embedded-runner/run/attempt.session-lock.test.ts
node scripts/run-vitest.mjs extensions/telegram/src/session-route.test.ts
npx tsx scripts/proof-84603-runtime.ts

Evidence after fix:

RUNTIME PROOF — PR #84603
Real session-key-utils + main-session imports
═══════════════════════════════════════════

── canonicalizeMainSessionAlias ──

  ✓ alias → canonicalized
    in:  agent:main:main
    out: agent:main:work
  ✓ threaded alias → unchanged (not an alias)
    in:  agent:main:main:thread:42
    out: agent:main:main:thread:42
  ✓ per-channel-peer → unchanged
    in:  agent:main:telegram:direct:123456
    out: agent:main:telegram:direct:123456

── Mirror decision guard (production logic) ──

  ✓ per-channel-peer (Telegram DM)
    sessionKey:          agent:main:telegram:direct:123456
    routed:              true
    targetsMainSession:  false
    baseIsMainSession:   false
    mirrorSuppressed:    true
  ✓ per-channel-peer (WhatsApp DM)
    sessionKey:          agent:main:whatsapp:direct:+15551234567
    routed:              true
    targetsMainSession:  false
    baseIsMainSession:   false
    mirrorSuppressed:    true
  ✓ per-channel-peer (Discord DM)
    sessionKey:          agent:main:discord:direct:987654
    routed:              true
    targetsMainSession:  false
    baseIsMainSession:   false
    mirrorSuppressed:    true
  ✓ threaded main session
    sessionKey:          agent:main:work:thread:42
    routed:              true
    targetsMainSession:  false
    baseIsMainSession:   true
    mirrorSuppressed:    false
  ✓ main session (explicit)
    sessionKey:          agent:main:main
    routed:              true
    targetsMainSession:  true
    baseIsMainSession:   true
    mirrorSuppressed:    false
  ✓ custom cron session (not routed)
    sessionKey:          agent:main:session:daily-report
    routed:              false
    targetsMainSession:  false
    baseIsMainSession:   false
    mirrorSuppressed:    false
  ✓ fallback agent session (not routed)
    sessionKey:          agent:main:telegram:123456
    routed:              false
    targetsMainSession:  false
    baseIsMainSession:   false
    mirrorSuppressed:    false

═══════════════════════════════════════════
  ALL CHECKS PASS
  7 passed, 0 failed
═══════════════════════════════════════════

Unit test results:

Test Files  4 passed (4)
     Tests  95 passed (95)

Observed result after fix:

  • Per-channel-peer sessions (Telegram/WhatsApp/Discord DM): mirror correctly suppressed — deliverySessionIsRoutedPeerSession = true
  • Threaded main-session variant: mirror still allowed — deliverySessionBaseIsMainSession = true correctly identifies it as a main-session variant
  • Main session explicit delivery: already handled by the awareness-queue guard (deliveryWillReachAwarenessMainSession), unchanged
  • Custom/fallback sessions (not routed): mirror still allowed, route = null so guard does not fire
  • Runtime proof: 7/7 mirror decision scenarios match expected behavior using real production imports (canonicalizeMainSessionAlias from src/config/sessions/main-session.js, parseThreadSessionSuffix from src/sessions/session-key-utils.js)
  • All 65 unit tests pass, all 3 acceptance-criteria test files pass, git diff --check clean

What was not tested: Live cron job delivering to a Telegram/WhatsApp/Discord channel while the same per-channel-peer session is held by an active embedded runner (requires live channel credentials, a configured cron job, and a concurrent embedded session). Same root pattern confirmed across cron and subagent announce paths (#84059).

🤖 Generated with Claude Code

@openclaw-barnacle openclaw-barnacle Bot added size: S triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 20, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed June 24, 2026, 6:13 AM ET / 10:13 UTC.

Summary
The PR changes cron direct delivery resolution to return outbound route metadata, skips transcript mirrors for routed non-main delivery sessions, updates cron delivery tests, and adds a PR-specific runtime proof script.

PR surface: Source +16, Tests +1, Other +201. Total +218 across 3 files.

Reproducibility: yes. source-level: current main and v2026.6.10 still resolve explicit cron delivery to a routed peer session and append a transcript mirror there. I did not run the live Telegram race in this read-only review.

Review metrics: 1 noteworthy metric.

  • Transcript behavior change: 1 routed-session mirror path suppressed. Existing per-channel-peer cron deliveries would stop writing durable peer transcript rows, which is the main compatibility tradeoff 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 merged work covers adjacent session-lock and awareness behavior but does not remove the unsafe mirror path on current main.

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 stronger real behavior proof is added.

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

Rank-up moves:

  • Resolve the current-main conflict and preserve merged cron target-awareness behavior.
  • [P1] Fix the canonical main/thread classification edge case and restore mirror-failure coverage.
  • [P1] Add redacted real cron/channel proof showing the direct delivery succeeds without EmbeddedAttemptSessionTakeoverError.

Proof guidance:

  • [P1] Needs stronger real behavior proof before merge: The PR body supplies terminal output from tests and a synthetic guard proof, but it does not show the changed cron/channel behavior in a real active Telegram or equivalent session; the contributor should add redacted live output, logs, a terminal capture, or recording, then update the PR body for re-review.

Mantis proof suggestion
A live Telegram proof would directly demonstrate that cron delivery to an active DM still sends the message and no longer aborts the in-flight chat turn. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis telegram desktop proof: verify an isolated cron delivery to an active Telegram DM still sends the cron message and does not trigger EmbeddedAttemptSessionTakeoverError.

Risk before merge

  • [P1] Merging this changes durable transcript behavior for routed peer cron deliveries: the visible channel send remains, but the local peer transcript mirror is intentionally suppressed.
  • [P1] The branch predates current cron target-awareness work and is currently conflicting, so a refresh must preserve merged target-session awareness, partial-delivery, and failure-awareness behavior.
  • [P1] The supplied proof is terminal output from focused tests and a synthetic guard script; it does not show a real cron delivery racing an active Telegram or equivalent channel session.

Maintainer options:

  1. Refresh and narrow the guard before merge (recommended)
    Resolve the current-main conflict, classify routed peer sessions with canonical route/base data, remove the PR-specific proof script, and restore mirror-failure coverage before requesting live proof.
  2. Accept the transcript-history tradeoff after proof
    Maintainers may choose the mirror-suppression behavior once live cron/channel proof shows direct delivery and target awareness still cover the user workflow.
  3. Replace with a clean canonical fix
    If the newer overlapping PR or a maintainer branch becomes clean, proven, and narrower, use that path and close this stale branch afterward.

Next step before merge

  • [P1] Human/contributor follow-up is needed because the branch is conflicting and the remaining blocker includes real channel proof that automation cannot supply for the contributor's setup.

Security
Cleared: The diff changes cron TypeScript logic, tests, and a local proof script without new dependencies, workflow permissions, package resolution, downloads, or secret handling.

Review findings

  • [P2] Canonicalize threaded main bases before suppressing mirrors — src/cron/isolated-agent/delivery-dispatch.ts:908-912
  • [P3] Remove the PR-specific proof script from scripts — scripts/proof-84603-runtime.ts:1
  • [P3] Keep mirror-failure coverage on an actual mirror path — src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts:1521-1529
Review details

Best possible solution:

Land a refreshed current-main fix that suppresses only unsafe routed peer transcript mirrors, preserves main and threaded-main behavior across alias/global scopes, keeps target-session awareness intact, and proves the cron/channel race with redacted real behavior evidence.

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

Yes, source-level: current main and v2026.6.10 still resolve explicit cron delivery to a routed peer session and append a transcript mirror there. I did not run the live Telegram race in this read-only review.

Is this the best way to solve the issue?

Not yet as submitted. The caller-side guard is the right layer for the narrow cron path, but it needs conflict resolution, canonical main/thread classification, restored coverage, and real cron/channel proof before it is the best mergeable fix.

Full review comments:

  • [P2] Canonicalize threaded main bases before suppressing mirrors — src/cron/isolated-agent/delivery-dispatch.ts:908-912
    This compares the parsed base key directly with awarenessMainSessionKey. In global-scope configs, the awareness key is global while threaded main aliases can still parse as agent:main:main, so the guard treats a routed threaded main delivery as a peer and suppresses the mirror despite the comment saying threaded main variants stay allowed. Classify against canonical route/base data and add a global-scope regression.
    Confidence: 0.82
  • [P3] Remove the PR-specific proof script from scripts — scripts/proof-84603-runtime.ts:1
    scripts/proof-84603-runtime.ts is a one-off PR proof harness named for this PR, not a maintained repo wrapper or check. Keeping review evidence as permanent script surface adds long-term repo debt; move this proof to the PR/artifact trail and convert any lasting assertions into focused tests.
    Confidence: 0.86
  • [P3] Keep mirror-failure coverage on an actual mirror path — src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts:1521-1529
    The test still claims to cover transcript mirror append failure, but the new main-session media-only setup goes through awareness suppression, so the mocked appendAssistantMessageToSessionTranscript rejection is unused. Use a custom cron session or threaded-main route where the mirror still runs, otherwise this PR drops coverage for the best-effort mirror-failure behavior.
    Confidence: 0.78

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 e9720c27fa69.

Label changes

Label justifications:

  • P2: The PR targets a real session-lock race that can abort user chat turns, but the trigger is bounded to cron routed-peer delivery and needs focused merge follow-up.
  • merge-risk: 🚨 compatibility: Suppressing routed-peer transcript mirrors can change existing users' session history and upgrade behavior for cron-delivered messages.
  • merge-risk: 🚨 session-state: The diff changes which session receives persistent transcript state versus queued awareness, and an incorrect guard can stale or mis-associate cron context.
  • 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 stronger real behavior proof before merge: The PR body supplies terminal output from tests and a synthetic guard proof, but it does not show the changed cron/channel behavior in a real active Telegram or equivalent session; the contributor should add redacted live output, logs, a terminal capture, or recording, then update the PR body for re-review.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The bug is observable in Telegram DM cron delivery, so a short Telegram Desktop or equivalent live proof would materially show the user-visible failure is gone.
Evidence reviewed

PR surface:

Source +16, Tests +1, Other +201. Total +218 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 23 7 +16
Tests 1 31 30 +1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 201 0 +201
Total 3 255 37 +218

What I checked:

  • Current main still mirrors routed delivery sessions: Current main resolves explicit cron delivery through outbound routing and then appends a transcript mirror when delivery succeeds unless only the existing main-session awareness guards apply; there is no routed-peer suppression in the mirror condition. (src/cron/isolated-agent/delivery-dispatch.ts:1198, e9720c27fa69)
  • Current resolver hides route classification from the mirror decision: The current resolver canonicalizes and returns only a session key, so the later mirror branch cannot distinguish a routed peer session from other non-main session keys. (src/cron/isolated-agent/delivery-dispatch.ts:678, e9720c27fa69)
  • Latest release still contains the unsafe mirror path: Tag v2026.6.10 has the same delivered direct-cron transcript mirror condition without a routed-peer guard, so current main's behavior is not already shipped-fixed. (src/cron/isolated-agent/delivery-dispatch.ts:1210, aa69b12d0086)
  • PR guard has a main-session alias edge case: The proposed guard compares the parsed delivery-session base directly to the awareness main-session key; global-scope main aliases resolve to global, while threaded aliases can still parse to agent:main:main, so a routed threaded main delivery can be treated as a peer and lose its mirror. (src/cron/isolated-agent/delivery-dispatch.ts:908, a7196a70950d)
  • PR branch is not landable as submitted: Live GitHub state reports mergeable: CONFLICTING and mergeStateStatus: DIRTY for the PR head, so it needs a current-main refresh before normal merge review. (a7196a70950d)
  • Feature history points to the cron mirror work: The destination-session cron mirror behavior was introduced in the merged cron delivery mirror series, including commits that changed the dispatcher, tests, and outbound session routing. (src/cron/isolated-agent/delivery-dispatch.ts, e16264312ac0)

Likely related people:

  • cavit99: Authored the merged cron destination-session transcript mirror work that added the central dispatcher behavior this PR narrows. (role: introduced behavior; confidence: high; commits: e16264312ac0, 88376c60af80; 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 mirror PR and authored an adjacent isolated delivery awareness-policy commit in the same feature series. (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)
  • scotthuang: Authored the merged target-session cron awareness work that this PR now has to preserve when suppressing durable mirrors. (role: recent adjacent contributor; confidence: high; commits: 80ff7df1063c, d89148674e36, 959ef86a7929; files: src/cron/isolated-agent/delivery-dispatch.ts, src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts)
  • jalehman: Merged the cron target-awareness PR and contributed several recent cron awareness/session-lock commits adjacent to this behavior. (role: recent adjacent contributor and merger; confidence: high; commits: 81abc2b21b03, 50898f3a3d25, 4339ebc41061; files: src/cron/isolated-agent/delivery-dispatch.ts, src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts, src/agents/embedded-agent-runner/run/attempt.session-lock.ts)
  • tianxiaochannel-oss88: Authored the merged embedded session-lock hardening that defines the owned-write boundary adjacent to this cron transcript race. (role: adjacent session-lock contributor; confidence: medium; commits: 3b630cdb7884, ff3066ef533e, 02cad4a33a6d; files: src/agents/embedded-agent-runner/run/attempt.session-lock.ts, src/config/sessions/transcript-write-context.ts, src/config/sessions/transcript.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.

@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. scripts Repository scripts size: M and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. size: S labels May 20, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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 May 20, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

This branch was previously deployed

1 inactive deployment
qa-live-shared — a7196a70 Deployed May 20, 2026 by clawsweeper[bot] via Run agentic native Telegram proof #34486
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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