Skip to content

Commit ef6fe66

Browse files
edenfunfVACInc
andauthored
fix(outbound): fence a delivery mirror against the session it writes into (#134083)
Co-authored-by: VACInc <[email protected]>
1 parent 24eb6d2 commit ef6fe66

7 files changed

Lines changed: 222 additions & 7 deletions

‎src/config/sessions/transcript-write-context.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
type SessionTranscriptRuntimeTarget,
1313
} from "./session-accessor.js";
1414
import {
15+
getOwnedSessionTranscriptWriterFence,
1516
SessionTranscriptWriterClaimReboundError,
1617
withOwnedSessionTranscriptWrites,
1718
} from "./transcript-write-context.js";
@@ -134,3 +135,73 @@ describe("owned transcript commit boundary", () => {
134135
},
135136
);
136137
});
138+
139+
describe("owned transcript writer fence scope", () => {
140+
const runningTarget = {
141+
agentId: "main",
142+
sessionKey: "agent:main:running",
143+
storePath: "/state/agents/main/openclaw-agent.sqlite",
144+
expectedLifecycleRevision: "rev-3",
145+
expectedWriterRunId: "run-running",
146+
};
147+
148+
async function withRunningWriter(run: () => void): Promise<void> {
149+
await withOwnedSessionTranscriptWrites(
150+
{
151+
sessionKey: runningTarget.sessionKey,
152+
sessionTarget: runningTarget,
153+
withTranscriptWrite: async (operation) => await operation(),
154+
},
155+
async () => run(),
156+
);
157+
}
158+
159+
it("inherits the fence for a caller that names the running session by key alone", async () => {
160+
await withRunningWriter(() => {
161+
expect(
162+
getOwnedSessionTranscriptWriterFence({ sessionKey: runningTarget.sessionKey }),
163+
).toEqual({
164+
expectedLifecycleRevision: "rev-3",
165+
expectedWriterRunId: "run-running",
166+
});
167+
});
168+
});
169+
170+
it("withholds the fence from a caller naming another session by key alone", async () => {
171+
await withRunningWriter(() => {
172+
// A key-only caller cannot form a target, so before this scoping it was refused by
173+
// the target comparison and fell back to the ambient claim - a claim about a
174+
// different session entirely.
175+
expect(
176+
getOwnedSessionTranscriptWriterFence({ sessionKey: "agent:main:elsewhere" }),
177+
).toBeUndefined();
178+
});
179+
});
180+
181+
it("still compares targets when the caller can express one", async () => {
182+
await withRunningWriter(() => {
183+
expect(getOwnedSessionTranscriptWriterFence({ sessionTarget: runningTarget })).toEqual({
184+
expectedLifecycleRevision: "rev-3",
185+
expectedWriterRunId: "run-running",
186+
});
187+
expect(
188+
getOwnedSessionTranscriptWriterFence({
189+
sessionTarget: {
190+
...runningTarget,
191+
storePath: "/state/agents/other/openclaw-agent.sqlite",
192+
},
193+
}),
194+
).toBeUndefined();
195+
});
196+
});
197+
198+
it("keeps the unscoped lookup reading the ambient claim", async () => {
199+
await withRunningWriter(() => {
200+
expect(getOwnedSessionTranscriptWriterFence()).toEqual({
201+
expectedLifecycleRevision: "rev-3",
202+
expectedWriterRunId: "run-running",
203+
});
204+
});
205+
expect(getOwnedSessionTranscriptWriterFence()).toBeUndefined();
206+
});
207+
});

‎src/config/sessions/transcript-write-context.ts‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,30 @@ function contextMatches(params: {
9090
return Boolean(contextSessionKey && sessionKey && contextSessionKey === sessionKey);
9191
}
9292

93+
/**
94+
* Ownership test for a writer fence, which is the one gate a caller can reach holding
95+
* nothing but a session key. A delivery mirror knows the session it writes into but not
96+
* that session's store path, so it cannot form a target; `contextMatches` would refuse
97+
* it for not being target-shaped and leave it unable to tell "the running session" from
98+
* "some other session". Compare keys in that case, and defer to the target comparison
99+
* whenever the caller can express one.
100+
*/
101+
function ownsRequestedSession(params: {
102+
context: OwnedSessionTranscriptWriteContext;
103+
sessionFile?: string;
104+
sessionKey?: string;
105+
sessionTarget?: SessionTranscriptWriteTarget;
106+
}): boolean {
107+
if (params.sessionTarget || params.sessionFile) {
108+
return contextMatches(params);
109+
}
110+
const contextSessionKey = (
111+
params.context.sessionTarget?.sessionKey ?? params.context.sessionKey
112+
)?.trim();
113+
const sessionKey = params.sessionKey?.trim();
114+
return Boolean(contextSessionKey && sessionKey && contextSessionKey === sessionKey);
115+
}
116+
93117
/** Runs transcript writes with the admitted run's teardown and writer-fence context. */
94118
export async function withOwnedSessionTranscriptWrites<T>(
95119
context: OwnedSessionTranscriptWriteContext,
@@ -110,7 +134,13 @@ export function bindOwnedSessionTranscriptWrites<TArgs extends unknown[], TResul
110134
return (...args) => ownedTranscriptWriteContext.run(context, () => run(...args));
111135
}
112136

113-
/** Returns the matching admitted-run fence for a durable write boundary. */
137+
/**
138+
* Returns the matching admitted-run fence for a durable write boundary.
139+
*
140+
* Every write boundary must name the session it writes into, or it inherits a claim
141+
* about whichever session happens to be running. Omitting the scope asks for the
142+
* ambient claim itself and is only for diagnostics that observe the running writer.
143+
*/
114144
export function getOwnedSessionTranscriptWriterFence(
115145
params: {
116146
sessionFile?: string;
@@ -119,7 +149,10 @@ export function getOwnedSessionTranscriptWriterFence(
119149
} = {},
120150
): SessionTranscriptWriterFence | undefined {
121151
const context = ownedTranscriptWriteContext.getStore();
122-
if (!context || (Object.keys(params).length > 0 && !contextMatches({ context, ...params }))) {
152+
if (
153+
!context ||
154+
(Object.keys(params).length > 0 && !ownsRequestedSession({ context, ...params }))
155+
) {
123156
return undefined;
124157
}
125158
const initial = context.initialWriter;

‎src/gateway/internal-source-reply-persistence.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ async function completePersistedInternalSourceReply(params: {
5454
scope.sessionKey = resolveSessionEntrySelection(scope).normalizedKey;
5555
const expected = {
5656
expectedSessionId: params.expectedSessionId,
57-
...getOwnedSessionTranscriptWriterFence(),
57+
...getOwnedSessionTranscriptWriterFence({ sessionKey: scope.sessionKey }),
5858
};
5959
const found = await findTranscriptEvent(scope, (event) => {
6060
const message = readTranscriptEventMessage(event);
@@ -171,7 +171,9 @@ export async function persistInternalSourceReply(params: {
171171
...(params.payload.text ? [{ type: "text", text: params.payload.text }] : []),
172172
...mediaBlocks,
173173
];
174-
const writerFence = getOwnedSessionTranscriptWriterFence();
174+
const writerFence = getOwnedSessionTranscriptWriterFence({
175+
sessionKey: params.sessionKey,
176+
});
175177
const appended = await appendAssistantMessageToSessionTranscript({
176178
agentId: params.agentId,
177179
sessionKey: params.sessionKey,

‎src/infra/outbound/deliver-transcript.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,9 @@ export async function mirrorDeliveredPayloads(params: {
4040
// Keep mirror failures non-fatal so callers do not retry an already-sent payload.
4141
try {
4242
const { appendAssistantMessageToSessionTranscript } = await loadTranscriptRuntime();
43-
const writerFence = getOwnedSessionTranscriptWriterFence();
43+
// Fence against the session this mirror lands in, not whichever run is delivering:
44+
// a cross-session delivery would otherwise carry the sending run's writer claim.
45+
const writerFence = getOwnedSessionTranscriptWriterFence({ sessionKey: mirror.sessionKey });
4446
const mirrorResult = await appendAssistantMessageToSessionTranscript({
4547
agentId: mirror.agentId,
4648
sessionKey: mirror.sessionKey,
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// Mirror fence tests cover which session's writer claim a delivery mirror carries.
2+
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
import { withOwnedSessionTranscriptWrites } from "../../config/sessions/transcript-write-context.js";
4+
import type { DeliverOutboundPayloadsCoreParams } from "./deliver-contracts.js";
5+
import { mirrorDeliveredPayloads } from "./deliver-transcript.js";
6+
import type { NormalizedOutboundPayload } from "./payloads.js";
7+
8+
const mocks = vi.hoisted(() => ({
9+
// Typed with the append params so the recorded call is inspectable without a cast.
10+
appendAssistantMessageToSessionTranscript: vi.fn(
11+
async (_params: Record<string, unknown>) => ({ ok: true }) as const,
12+
),
13+
}));
14+
15+
vi.mock("../../config/sessions/transcript.runtime.js", async () => {
16+
const actual = await vi.importActual<
17+
typeof import("../../config/sessions/transcript.runtime.js")
18+
>("../../config/sessions/transcript.runtime.js");
19+
return {
20+
...actual,
21+
appendAssistantMessageToSessionTranscript: mocks.appendAssistantMessageToSessionTranscript,
22+
};
23+
});
24+
25+
const RUNNING_SESSION_KEY = "agent:wolf:discord:channel:1497965766035640391";
26+
const OTHER_SESSION_KEY = "agent:arthur:discord:channel:1538510183024689305";
27+
28+
function payload(text: string): NormalizedOutboundPayload {
29+
return { text, mediaUrls: [] };
30+
}
31+
32+
async function mirrorInto(sessionKey: string): Promise<void> {
33+
await mirrorDeliveredPayloads({
34+
delivery: {
35+
cfg: {},
36+
mirror: { agentId: "wolf", sessionKey },
37+
} as unknown as DeliverOutboundPayloadsCoreParams,
38+
payloads: [payload("delivered to the user")],
39+
channel: "discord",
40+
to: "1497965766035640391",
41+
});
42+
}
43+
44+
/** Runs a mirror inside a run that owns `RUNNING_SESSION_KEY`, the way a live delivery does. */
45+
async function withRunningSession(run: () => Promise<void>): Promise<void> {
46+
await withOwnedSessionTranscriptWrites(
47+
{
48+
sessionKey: RUNNING_SESSION_KEY,
49+
sessionTarget: {
50+
agentId: "wolf",
51+
sessionKey: RUNNING_SESSION_KEY,
52+
storePath: "/state/agents/wolf/openclaw-agent.sqlite",
53+
expectedLifecycleRevision: "rev-7",
54+
expectedWriterRunId: "run-running",
55+
},
56+
withTranscriptWrite: async (operation) => await operation(),
57+
},
58+
run,
59+
);
60+
}
61+
62+
function appendedArgs() {
63+
return mocks.appendAssistantMessageToSessionTranscript.mock.calls[0]?.[0];
64+
}
65+
66+
describe("outbound delivery mirror writer fence", () => {
67+
beforeEach(() => {
68+
mocks.appendAssistantMessageToSessionTranscript.mockClear();
69+
mocks.appendAssistantMessageToSessionTranscript.mockResolvedValue({ ok: true } as const);
70+
});
71+
72+
it("carries the running run's fence when it mirrors into that run's own session", async () => {
73+
await withRunningSession(async () => {
74+
await mirrorInto(RUNNING_SESSION_KEY);
75+
});
76+
77+
expect(appendedArgs()).toMatchObject({
78+
sessionKey: RUNNING_SESSION_KEY,
79+
expectedWriterRunId: "run-running",
80+
expectedLifecycleRevision: "rev-7",
81+
});
82+
});
83+
84+
it("withholds that fence when it mirrors into a different session", async () => {
85+
await withRunningSession(async () => {
86+
await mirrorInto(OTHER_SESSION_KEY);
87+
});
88+
89+
const args = appendedArgs();
90+
expect(args).toMatchObject({ sessionKey: OTHER_SESSION_KEY });
91+
// A claim about the delivering session is not a claim about this one. Passing it made
92+
// the transcript guards refuse the append as "session rebound", and the refusal is
93+
// warn-only after a successful channel send, so the mirror was lost for good.
94+
expect(args).not.toHaveProperty("expectedWriterRunId");
95+
expect(args).not.toHaveProperty("expectedLifecycleRevision");
96+
});
97+
98+
it("mirrors unfenced when no run owns a transcript write", async () => {
99+
await mirrorInto(RUNNING_SESSION_KEY);
100+
101+
const args = appendedArgs();
102+
expect(args).toMatchObject({ sessionKey: RUNNING_SESSION_KEY });
103+
expect(args).not.toHaveProperty("expectedWriterRunId");
104+
});
105+
});

‎src/infra/outbound/outbound-send-service.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,9 @@ export async function executeSendAction(params: {
446446
params.mediaUrls ??
447447
(params.mediaUrl ? [params.mediaUrl] : undefined);
448448
try {
449-
const writerFence = getOwnedSessionTranscriptWriterFence();
449+
const writerFence = getOwnedSessionTranscriptWriterFence({
450+
sessionKey: params.ctx.mirror.sessionKey,
451+
});
450452
const mirrorResult = await appendAssistantMessageToSessionTranscript({
451453
agentId: params.ctx.mirror.agentId,
452454
sessionKey: params.ctx.mirror.sessionKey,

‎src/infra/outbound/source-reply-mirror.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,7 @@ export async function mirrorDeliveredSourceReplyToTranscript(
594594
return false;
595595
}
596596
const sourceTurnId = resolveCurrentSourceTurnId(params.toolContext);
597-
const writerFence = getOwnedSessionTranscriptWriterFence();
597+
const writerFence = getOwnedSessionTranscriptWriterFence({ sessionKey: params.sessionKey });
598598
const result = await appendAssistantMessageToSessionTranscript({
599599
agentId: params.agentId,
600600
sessionKey: params.sessionKey,

0 commit comments

Comments
 (0)