Skip to content

fix(sessions): scope the outbound transcript mirror fence to its destination - #132852

Closed
ruel225 wants to merge 1 commit into
openclaw:mainfrom
ruel225:fix/mirror-writer-fence-destination-132766
Closed

ruel225 wants to merge 1 commit into
openclaw:mainfrom
ruel225:fix/mirror-writer-fence-destination-132766

Conversation

@ruel225

@ruel225 ruel225 commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

mirrorDeliveredPayloads and its three sibling mirror boundaries write a delivered payload into the destination session's transcript, but acquired their transcript writer fence by calling getOwnedSessionTranscriptWriterFence() with no arguments.

That function only runs its contextMatches gate when it was given parameters, so the zero-arg call skipped the gate and returned the ambient admitted run's expectedWriterRunId / expectedLifecycleRevision — a writer claim about the sending run's session, not the session receiving the mirror. The transcript guards then refused the append as session rebound, the refusal was warn-only, and the channel send had already succeeded, so the mirror was never retried. The receiving session kept answering while having silently lost every mirrored delivery.

Reported with 18 occurrences across 5 session keys and 3 agents in a real multi-agent gateway, including 8 of 8 deliveries on one channel across four consecutive days. A sessions.reset on the target key (rotating lifecycleRevision, clearing activeWriterRunId) restored mirroring on the very next delivery, which is what isolated the mechanism.

Why This Change Was Made

Two connected defects share one invariant: a transcript write may only inherit the admitted run's writer claim when the write's destination is that run's session.

  1. The four mirror boundaries looked the fence up with no destination identity at all, so they could not be scoped. Affected: src/infra/outbound/deliver-transcript.ts, src/infra/outbound/outbound-send-service.ts, src/infra/outbound/source-reply-mirror.ts, and src/gateway/internal-source-reply-persistence.ts (the fourth zero-arg call site, same invariant, found while reading the fence's consumers).
  2. contextMatches rejected a session-key-only request outright whenever the ambient context carried a sessionTarget: the branch condition was params.context.sessionTarget || params.sessionTarget, so a request without a target produced requestedTarget === undefined and returned false for every destination, including the correct one. Fixing only (1) would have stripped the fence from same-session mirrors too.

The fix names the destination session at all four boundaries and teaches the gate to match session-key-only requests against the owning run's session identity. Callers that pass a full sessionTarget still require the exact store identity (sessionKey + storePath), so the SQLite write scopes (withOwnedSessionTranscriptWriterFence at the four sync write sites and runWithOwnedSessionTranscriptWrite at the turn boundaries) are byte-for-byte unaffected.

User Impact

Cross-session outbound mirrors (announce/handoff from another session, message sends into another session key) now land in the destination session's transcript instead of being silently discarded. Same-session mirrors keep their writer-claim protection, so a concurrent writer change is still detected. No config, default, or operator action changes.

Evidence

Reproduction and regression tests (pre-fix failure confirmed by running before the fix):

  • src/infra/outbound/deliver-transcript.test.ts — drives the real mirrorDeliveredPayloads under an ambient admitted-run context for session A while mirroring into session B. Pre-fix, the append received expectedWriterRunId: "run-agent:main:discord:c:1" (session A's claim) for a write into session B. Post-fix it receives no claim. The companion case pins that a mirror into the run's own session still forwards expectedWriterRunId and expectedLifecycleRevision, guarding against over-correction.
  • src/config/sessions/transcript-write-context.test.ts — pins the gate invariant: session-key-only requests match the owning session, reject a different destination, and full-target requests still require an exact store-identity match. The third case failed before the gate change for the owning session too, which is why the gate relaxation is part of this fix rather than an optional extra.

Sibling coverage (no regression):

  • node scripts/run-vitest.mjs run src/infra/outbound/ — 100 files, 1653 tests passed. Covers message-action-runner, which is the sole consumer of persistInternalSourceReply.
  • node scripts/run-vitest.mjs run src/config/sessions/session-accessor.conformance.test.ts src/config/sessions/transcript.test.ts — 111 tests passed.
  • node scripts/run-vitest.mjs run src/agents/tools/sessions.test.ts — 95 tests passed.
  • node scripts/run-vitest.mjs run src/infra/heartbeat-wake.transcript-context.test.ts — passed (ambient-context isolation).
  • node scripts/run-tsgo.mjs -p tsconfig.core.json clean; oxlint and oxfmt --check clean on all touched files.

Production diff: 5 files, +18/−6. The growth is the destination identity threaded into four independent mirror boundaries plus the gate's session-identity branch and its invariant comment; there is no wrapper or helper that absorbs it, and deleting the same-session fence (the only way to reach net zero) would remove real writer-claim protection.

Rebase onto current main (2026-08-30)

main (b4f8510) has since introduced the initial-writer lease (InitialSessionTranscriptWriter + assertCommitAllowed) as the custody mechanism around these same boundaries. This branch was rewritten onto that baseline as a single commit (f612443); the CONFLICTING state is resolved.

  • The two gate semantics from this PR are unchanged and land cleanly on the new mechanism; the lease revalidation composes with the destination-scoped fence lookup.
  • The four destination-scoped call sites are re-applied. persistInternalSourceReply now sits inside main's media-cleanup try/finally; the read-side zero-arg fence lookup at the replay/idempotency probe is intentionally untouched, matching the original scope.
  • Pre-fix failure on the rewritten baseline (gate revert only): AssertionError: expected undefined to deeply equal { …(2) } — with the old gate, the owning session key resolves no claim whenever the ambient context carries a session target (1 failed | 12 passed; post-fix 13 passed). This pins why the gate relaxation is part of the fix rather than an optional extra.
  • Sibling coverage on the rewritten baseline: transcript-write-context.test.ts 13 passed, internal-source-reply-persistence.test.ts 47 passed, source-reply-mirror.test.ts 10 passed, outbound-send-service + message-action-send.mirror-order passed, deliver-transcript.test.ts 2 passed. oxlint clean on all touched files.

@clawsweeper

clawsweeper Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Aug 29, 2026
@ruel225
ruel225 marked this pull request as ready for review August 29, 2026 21:12
@clawsweeper clawsweeper Bot added 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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 29, 2026
@clawsweeper

clawsweeper Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 30, 2026, 9:57 AM ET / 13:57 UTC.

ClawSweeper review

What this changes

The branch passes each outbound mirror’s destination session key into the transcript writer-fence lookup and adds regression coverage for cross-session versus same-session behavior.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 4 items remain

Keep open: current main still applies an ambient writer fence to outbound mirrors, while the branch scopes it to the destination and preserves same-session fencing. The code and focused regression coverage support the repair, but the external PR still lacks inspectable real after-fix behavior proof.

Priority: P1
Reviewed head: f6124437211b40e72dd21b555bb4a63eb54514e3

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused repair and regression coverage are sound on source review, but real after-fix behavior proof remains the merge gate.
Proof confidence 🦪 silver shellfish (2/6) Needs stronger real behavior proof before merge: The changed production owners are the four outbound mirror fence lookups and their transcript append calls; the supplied test exercises one owner through AsyncLocalStorage but mocks the append, and no inspectable real gateway/store after-fix result was provided. Two filtered comments could not be retrieved because GitHub access was unavailable. 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.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The changed production owners are the four outbound mirror fence lookups and their transcript append calls; the supplied test exercises one owner through AsyncLocalStorage but mocks the append, and no inspectable real gateway/store after-fix result was provided. Two filtered comments could not be retrieved because GitHub access was unavailable. 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.
Evidence reviewed 6 items Current-main behavior remains unfixed: At fetched main, the mirror calls the fence lookup without destination identity, while the matcher rejects a key-only request whenever the ambient context has a full target.
Destination ownership repair: The branch retains full store-identity matching for callers that supply a target, then matches key-only mirror requests against the context target’s session key.
Production caller and callee: Core delivery invokes the mirror after the transport loop, and the mirror forwards the destination key and any matching fence to the transcript append owner.
Findings None None.
Security None None.

How this fits together

Outbound delivery sends a payload through a channel and then mirrors the delivered content into a session transcript. The transcript writer fence carries an admitted run’s concurrency claim only when that transcript destination is the admitted session.

flowchart LR
  A[Admitted run] --> B[Writer fence context]
  C[Channel delivery] --> D[Outbound mirror]
  D --> E[Destination session key]
  B --> F{Destination matches admitted session?}
  E --> F
  F -->|yes| G[Claimed transcript append]
  F -->|no| H[Unclaimed destination append]
  G --> I[Session transcript]
  H --> I
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The changed production owners are the four outbound mirror fence lookups and their transcript append calls; the supplied test exercises one owner through AsyncLocalStorage but mocks the append, and no inspectable real gateway/store after-fix result was provided. Two filtered comments could not be retrieved because GitHub access was unavailable. 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.
  • Resolve merge risk (P1) - The changed session-state boundary is demonstrated only with mocked append calls; before merge, inspect a redacted after-fix gateway/store trace showing a cross-session mirror lands and a stale same-session writer remains rejected.
  • Resolve merge risk (P1) - Production changes are net +12 lines for this bug fix; the four destination-specific owners and shared matcher appear necessary, but their runtime behavior still needs real-boundary confirmation.
  • Complete next step (P2) - The remaining blocker is contributor-supplied real behavior proof, not a mechanical repair suitable for an automated fix lane.
Agent review details

Security

None.

PR surface

Source +12, Tests +160. Total +172 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 5 18 6 +12
Tests 2 160 0 +160
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 178 6 +172

Review metrics

Metric Value Why it matters
Production versus test delta production +12, tests +160 The production growth is limited to four destination lookups and the matcher; the test growth exercises the fence invariant and one delivery boundary.

Merge-risk options

Maintainer options:

  1. Add real transcript-store proof (recommended)
    Attach redacted after-fix evidence from a real gateway/store run covering cross-session delivery and the retained same-session writer fence.

Technical review

Best possible solution:

Preserve the direct destination-key lookups and shared matcher, then demonstrate the cross-session destination append and same-session stale-writer rejection through the real transcript store.

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

Yes: current main’s zero-argument lookup returns the ambient claim, and a mirror then supplies that claim while appending to its destination session. The supplied focused tests model the cross-session and same-session cases, though this review did not execute untrusted contributor code.

Is this the best way to solve the issue?

Yes: destination-scoped lookup at each independently owned mirror boundary, with the existing full-target matcher retained, is the narrowest coherent repair found.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: This repairs a reported silent loss of mirrored transcript entries in active outbound session workflows.
  • merge-risk: 🚨 session-state: The change determines when lifecycle and writer-run claims are applied to persisted session transcript writes.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The changed production owners are the four outbound mirror fence lookups and their transcript append calls; the supplied test exercises one owner through AsyncLocalStorage but mocks the append, and no inspectable real gateway/store after-fix result was provided. Two filtered comments could not be retrieved because GitHub access was unavailable. 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.

Evidence

What I checked:

Likely related people:

  • unidentified: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Attach redacted real gateway/store evidence for a cross-session append and stale same-session-writer rejection.
  • Update the PR body after adding proof; that should trigger a fresh ClawSweeper review automatically.

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 (5 earlier review cycles)
  • reviewed 2026-08-29T21:20:04.169Z sha 00ec1ec16c7b54cadd1fbc3a29c9fc35098fde12 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-29T22:51:02.467Z sha 012c51fe673c20a3281487c8f109b1aa452c0feb :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-30T00:32:50.325Z sha f57b9c2b983c5ed51c644e155a396424a0ec7a98 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-30T00:57:09.867Z sha 340be12e9c2df6d0b9ec6474d0385e320e47cff4 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-30T01:24:07.265Z sha 2d6c3f557ecf5b07666024ab1fe02e5d161274a5 :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 29, 2026
…ination

Outbound mirror writes fetched the ambient transcript writer fence with
no destination scoping, and the ambient context carries the sending
run's session target, so every session-key-only call failed the
store-identity match and silently dropped the fence. Mirror appends
then lost optimistic-concurrency protection against the owning writer.

Match the fence to the mirror's destination session key instead, and
let session-key-only callers resolve the ambient claim through the
context's target session key.

Co-Authored-By: Claude <[email protected]>
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Superseded by #134083, merged to main as ef6fe66.

The landed repair covers all five destination-scoped writer-fence lookups, including the internal replay path, while keeping the shared full-target comparator strict. This PR leaves that replay lookup unscoped and changes broader matching semantics, so closing it as the incomplete duplicate.

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

Labels

gateway Gateway runtime 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. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S 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.

2 participants