Skip to content

Commit 04f945f

Browse files
authored
feat(cloud-workers): durable transcript commit protocol for worker sessions (#104809)
* feat(cloud-workers): add transcript commit protocol * feat(cloud-workers): persist transcript commit replay state * feat(cloud-workers): apply transcript commits to sessions * fix(cloud-workers): harden transcript commit admission * fix(cloud-workers): recover branched transcript commits * fix(cloud-workers): preserve diagnostic semantics
1 parent 2e6c109 commit 04f945f

25 files changed

Lines changed: 2908 additions & 28 deletions

‎docs/gateway/protocol.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,8 +176,12 @@ verifies a hash-at-rest, short-lived credential bound to the environment, bundle
176176
hash, owner epoch, RPC-set version, expiry, and one nullable session; it
177177
separately checks the current version and feature set. Success returns minimal
178178
`worker-hello-ok`; feature negotiation is independent of the general protocol
179-
version. Frames stay under 64 KiB. Initially only `worker.heartbeat` is allowed,
180-
with ownership and expiry rechecked on each RPC.
179+
version. Frames stay under 64 KiB. The closed allowlist contains
180+
`worker.heartbeat` and `worker.transcript.commit` for ordered semantic message batches. Transcript
181+
commits use owner-epoch fencing, a gateway-owned session binding, base-leaf
182+
compare-and-swap, and durable sequence replay; the gateway generates transcript
183+
entry and parent IDs through the normal session writer. Ownership and expiry are
184+
rechecked on each RPC.
181185

182186
### Client capabilities
183187

‎packages/gateway-protocol/src/index.ts‎

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,20 @@ import {
421421
type WorkerHelloOk,
422422
type WorkerProtocolCloseReason,
423423
WorkerProtocolCloseReasonSchema,
424+
type WorkerTranscriptCommitErrorReason,
425+
WorkerTranscriptCommitErrorReasonSchema,
426+
type WorkerTranscriptCommitErrorShape,
427+
WorkerTranscriptCommitErrorShapeSchema,
428+
type WorkerTranscriptCommitParams,
429+
WorkerTranscriptCommitParamsSchema,
430+
type WorkerTranscriptCommitRequestFrame,
431+
WorkerTranscriptCommitRequestFrameSchema,
432+
type WorkerTranscriptCommitResponseFrame,
433+
WorkerTranscriptCommitResponseFrameSchema,
434+
type WorkerTranscriptCommitResult,
435+
WorkerTranscriptCommitResultSchema,
436+
type WorkerTranscriptMessage,
437+
WorkerTranscriptMessageSchema,
424438
WORKER_HEARTBEAT_INTERVAL_MS,
425439
WORKER_PROTOCOL_FEATURES,
426440
WORKER_PROTOCOL_MAX_FEATURE_LENGTH,
@@ -431,6 +445,10 @@ import {
431445
WORKER_PROTOCOL_MAX_PAYLOAD_BYTES,
432446
WORKER_PROTOCOL_METHODS,
433447
WORKER_RPC_SET_VERSION,
448+
WORKER_TRANSCRIPT_MAX_BATCH_MESSAGES,
449+
WORKER_TRANSCRIPT_MAX_CONTENT_PARTS,
450+
WORKER_TRANSCRIPT_MAX_JSON_DEPTH,
451+
WORKER_TRANSCRIPT_COMMIT_PROTOCOL_FEATURE,
434452
type SystemInfoParams,
435453
SystemInfoParamsSchema,
436454
type SystemInfoResult,
@@ -861,7 +879,10 @@ export type ProtocolValidator<T = unknown> = ((data: unknown) => data is T) & {
861879

862880
// Defer TypeBox compilation until the first validation call. Importing this
863881
// module is common in CLIs/tests, so eager compilation would add startup cost.
864-
function lazyCompile<T = unknown>(schema: unknown): ProtocolValidator<T> {
882+
function lazyCompile<T = unknown>(
883+
schema: unknown,
884+
precheck?: (data: unknown) => ValidationError | undefined,
885+
): ProtocolValidator<T> {
865886
let compiled: TypeBoxValidator | undefined;
866887
let errors: ValidationError[] | null = null;
867888

@@ -871,6 +892,11 @@ function lazyCompile<T = unknown>(schema: unknown): ProtocolValidator<T> {
871892
};
872893

873894
const validate = ((data: unknown): data is T => {
895+
const precheckError = precheck?.(data);
896+
if (precheckError) {
897+
errors = [precheckError];
898+
return false;
899+
}
874900
const current = getCompiled();
875901
const valid = current.Check(data);
876902
errors = valid ? null : ([...current.Errors(data)] as ValidationError[]);
@@ -910,6 +936,56 @@ export const validateWorkerConnectRequestFrame = lazyCompile<WorkerConnectReques
910936
export const validateWorkerHeartbeatParams = lazyCompile<WorkerHeartbeatParams>(
911937
WorkerHeartbeatParamsSchema,
912938
);
939+
940+
function checkWorkerTranscriptCommitJson(data: unknown): ValidationError | undefined {
941+
const stack: Array<{ depth: number; value: unknown }> = [{ depth: 0, value: data }];
942+
const seen = new WeakSet<object>();
943+
while (stack.length > 0) {
944+
const current = stack.pop();
945+
if (!current) {
946+
break;
947+
}
948+
if (current.depth > WORKER_TRANSCRIPT_MAX_JSON_DEPTH) {
949+
return {
950+
keyword: "maxDepth",
951+
params: { limit: WORKER_TRANSCRIPT_MAX_JSON_DEPTH },
952+
message: `must not exceed JSON nesting depth ${WORKER_TRANSCRIPT_MAX_JSON_DEPTH}`,
953+
};
954+
}
955+
if (
956+
current.value === null ||
957+
typeof current.value === "string" ||
958+
typeof current.value === "boolean"
959+
) {
960+
continue;
961+
}
962+
if (typeof current.value === "number") {
963+
if (!Number.isFinite(current.value)) {
964+
return { keyword: "finite", message: "must contain only finite JSON numbers" };
965+
}
966+
continue;
967+
}
968+
if (typeof current.value !== "object") {
969+
return { keyword: "jsonValue", message: "must contain only JSON values" };
970+
}
971+
if (seen.has(current.value)) {
972+
return { keyword: "acyclic", message: "must be an acyclic JSON value" };
973+
}
974+
seen.add(current.value);
975+
const values = Array.isArray(current.value)
976+
? current.value
977+
: Object.values(current.value as Record<string, unknown>);
978+
for (const value of values) {
979+
stack.push({ depth: current.depth + 1, value });
980+
}
981+
}
982+
return undefined;
983+
}
984+
985+
export const validateWorkerTranscriptCommitParams = lazyCompile<WorkerTranscriptCommitParams>(
986+
WorkerTranscriptCommitParamsSchema,
987+
checkWorkerTranscriptCommitJson,
988+
);
913989
export const validateGatewaySuspendPrepareParams = lazyCompile<GatewaySuspendPrepareParams>(
914990
GatewaySuspendPrepareParamsSchema,
915991
);
@@ -1517,6 +1593,13 @@ export {
15171593
WorkerHeartbeatRequestFrameSchema,
15181594
WorkerHeartbeatResponseFrameSchema,
15191595
WorkerProtocolCloseReasonSchema,
1596+
WorkerTranscriptCommitErrorReasonSchema,
1597+
WorkerTranscriptCommitErrorShapeSchema,
1598+
WorkerTranscriptCommitParamsSchema,
1599+
WorkerTranscriptCommitRequestFrameSchema,
1600+
WorkerTranscriptCommitResponseFrameSchema,
1601+
WorkerTranscriptCommitResultSchema,
1602+
WorkerTranscriptMessageSchema,
15201603
WORKER_HEARTBEAT_INTERVAL_MS,
15211604
WORKER_PROTOCOL_FEATURES,
15221605
WORKER_PROTOCOL_MAX_FEATURE_LENGTH,
@@ -1527,6 +1610,10 @@ export {
15271610
WORKER_PROTOCOL_MAX_PAYLOAD_BYTES,
15281611
WORKER_PROTOCOL_METHODS,
15291612
WORKER_RPC_SET_VERSION,
1613+
WORKER_TRANSCRIPT_MAX_BATCH_MESSAGES,
1614+
WORKER_TRANSCRIPT_MAX_CONTENT_PARTS,
1615+
WORKER_TRANSCRIPT_MAX_JSON_DEPTH,
1616+
WORKER_TRANSCRIPT_COMMIT_PROTOCOL_FEATURE,
15301617
EnvironmentStatusSchema,
15311618
WorkerEnvironmentStateSchema,
15321619
WorkerTunnelStatusSchema,
@@ -1902,6 +1989,13 @@ export type {
19021989
WorkerHeartbeatResponseFrame,
19031990
WorkerHelloOk,
19041991
WorkerProtocolCloseReason,
1992+
WorkerTranscriptCommitErrorReason,
1993+
WorkerTranscriptCommitErrorShape,
1994+
WorkerTranscriptCommitParams,
1995+
WorkerTranscriptCommitRequestFrame,
1996+
WorkerTranscriptCommitResponseFrame,
1997+
WorkerTranscriptCommitResult,
1998+
WorkerTranscriptMessage,
19051999
GatewaySuspendTaskBlocker,
19062000
GatewaySuspendBlocker,
19072001
GatewaySuspendPrepareParams,

‎packages/gateway-protocol/src/schema/worker-admission.test.ts‎

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,14 @@ import {
77
WorkerHeartbeatRequestFrameSchema,
88
WorkerHeartbeatResponseFrameSchema,
99
WorkerProtocolCloseReasonSchema,
10+
WorkerTranscriptCommitRequestFrameSchema,
11+
WorkerTranscriptCommitResponseFrameSchema,
1012
WORKER_RPC_SET_VERSION,
13+
WORKER_TRANSCRIPT_MAX_JSON_DEPTH,
1114
validateWorkerAdmissionHandshake,
1215
validateWorkerConnectRequestFrame,
1316
validateWorkerHeartbeatParams,
17+
validateWorkerTranscriptCommitParams,
1418
} from "../index.js";
1519

1620
const bundleHash = "a".repeat(64);
@@ -49,6 +53,46 @@ const workerHello = {
4953
credentialExpiresAtMs: 10_000,
5054
policy: { heartbeatIntervalMs: 15_000, maxPayload: 1_024 },
5155
};
56+
const usage = {
57+
input: 1,
58+
output: 2,
59+
cacheRead: 0,
60+
cacheWrite: 0,
61+
totalTokens: 3,
62+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
63+
};
64+
const transcriptMessages = [
65+
{
66+
role: "user" as const,
67+
content: [{ type: "text" as const, text: "run the probe" }],
68+
timestamp: 1,
69+
},
70+
{
71+
role: "assistant" as const,
72+
content: [
73+
{
74+
type: "toolCall" as const,
75+
id: "call-1",
76+
name: "probe",
77+
arguments: { value: 1 },
78+
},
79+
],
80+
api: "responses",
81+
provider: "fixture",
82+
model: "fixture-model",
83+
usage,
84+
stopReason: "toolUse" as const,
85+
timestamp: 2,
86+
},
87+
{
88+
role: "toolResult" as const,
89+
toolCallId: "call-1",
90+
toolName: "probe",
91+
content: [{ type: "text" as const, text: "ok" }],
92+
isError: false,
93+
timestamp: 3,
94+
},
95+
];
5296

5397
describe("worker admission handshake schema", () => {
5498
it("accepts the bootstrap receipt and future unique feature names", () => {
@@ -112,6 +156,139 @@ describe("worker protocol schemas", () => {
112156
expect(Value.Check(WorkerHeartbeatResponseFrameSchema, response)).toBe(true);
113157
});
114158

159+
it("accepts semantic transcript commits and generated-id responses", () => {
160+
const params = {
161+
runEpoch: 2,
162+
seq: 1,
163+
baseLeafId: null,
164+
messages: transcriptMessages,
165+
};
166+
expect(validateWorkerTranscriptCommitParams(params)).toBe(true);
167+
expect(
168+
Value.Check(WorkerTranscriptCommitRequestFrameSchema, {
169+
type: "req",
170+
id: "commit-1",
171+
method: "worker.transcript.commit",
172+
params,
173+
}),
174+
).toBe(true);
175+
expect(
176+
Value.Check(WorkerTranscriptCommitResponseFrameSchema, {
177+
type: "res",
178+
id: "commit-1",
179+
ok: true,
180+
payload: { entryIds: ["entry-1", "entry-2", "entry-3"], newLeafId: "entry-3" },
181+
}),
182+
).toBe(true);
183+
expect(
184+
Value.Check(WorkerTranscriptCommitResponseFrameSchema, {
185+
type: "res",
186+
id: "commit-1",
187+
ok: false,
188+
error: {
189+
code: "INVALID_REQUEST",
190+
message: "worker request rejected",
191+
details: { reason: "credential-replaced" },
192+
},
193+
}),
194+
).toBe(true);
195+
expect(
196+
Value.Check(WorkerTranscriptCommitResponseFrameSchema, {
197+
type: "res",
198+
id: "commit-1",
199+
ok: false,
200+
error: {
201+
code: "INVALID_REQUEST",
202+
message: "transcript commit rejected",
203+
details: { reason: "stale-base-leaf" },
204+
},
205+
}),
206+
).toBe(true);
207+
});
208+
209+
it.each([
210+
{ runEpoch: 2, seq: 1, baseLeafId: null, messages: [] },
211+
{ runEpoch: 2, seq: 0, baseLeafId: null, messages: transcriptMessages },
212+
{ runEpoch: 2, seq: 1, baseLeafId: null, messages: transcriptMessages, sessionId: "other" },
213+
{
214+
runEpoch: 2,
215+
seq: 1,
216+
baseLeafId: null,
217+
messages: [{ ...transcriptMessages[0], id: "entry-from-worker" }],
218+
},
219+
{
220+
runEpoch: 2,
221+
seq: 1,
222+
baseLeafId: null,
223+
messages: [{ ...transcriptMessages[0], parentId: "parent-from-worker" }],
224+
},
225+
{
226+
runEpoch: 2,
227+
seq: 1,
228+
baseLeafId: null,
229+
messages: [{ ...transcriptMessages[0], sessionId: "foreign-session" }],
230+
},
231+
])("rejects raw transcript identity or invalid batch fields %#", (candidate) => {
232+
expect(validateWorkerTranscriptCommitParams(candidate)).toBe(false);
233+
});
234+
235+
it("rejects deeply nested worker JSON before schema compilation", () => {
236+
let nested: unknown = "leaf";
237+
for (let depth = 0; depth <= WORKER_TRANSCRIPT_MAX_JSON_DEPTH; depth += 1) {
238+
nested = { nested };
239+
}
240+
const assistant = transcriptMessages[1];
241+
if (!assistant || assistant.role !== "assistant") {
242+
throw new Error("expected assistant transcript fixture");
243+
}
244+
const candidate = {
245+
runEpoch: 2,
246+
seq: 1,
247+
baseLeafId: null,
248+
messages: [
249+
{
250+
...assistant,
251+
content: [
252+
{
253+
type: "toolCall" as const,
254+
id: "call-deep",
255+
name: "probe",
256+
arguments: { nested },
257+
},
258+
],
259+
},
260+
],
261+
};
262+
263+
expect(validateWorkerTranscriptCommitParams(candidate)).toBe(false);
264+
expect(validateWorkerTranscriptCommitParams.errors?.[0]).toMatchObject({
265+
keyword: "maxDepth",
266+
params: { limit: WORKER_TRANSCRIPT_MAX_JSON_DEPTH },
267+
});
268+
});
269+
270+
it("rejects non-finite numbers parsed from worker JSON", () => {
271+
const candidate = JSON.parse(`{
272+
"runEpoch": 2,
273+
"seq": 1,
274+
"baseLeafId": null,
275+
"messages": [{
276+
"role": "toolResult",
277+
"toolCallId": "call-non-finite",
278+
"toolName": "probe",
279+
"content": [],
280+
"details": { "value": 1e400 },
281+
"isError": false,
282+
"timestamp": 1
283+
}]
284+
}`) as unknown;
285+
286+
expect(validateWorkerTranscriptCommitParams(candidate)).toBe(false);
287+
expect(validateWorkerTranscriptCommitParams.errors?.[0]).toMatchObject({
288+
keyword: "finite",
289+
});
290+
});
291+
115292
it("keeps worker close reasons closed", () => {
116293
expect(Value.Check(WorkerProtocolCloseReasonSchema, "credential-replaced")).toBe(true);
117294
expect(Value.Check(WorkerProtocolCloseReasonSchema, "not-a-worker-reason")).toBe(false);

0 commit comments

Comments
 (0)