Skip to content

Commit 9910c0e

Browse files
Bil0000juliusmarmingeclaude
authored
perf: reduce remote reconnect and command delays (#25754)
Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent ff71186 commit 9910c0e

7 files changed

Lines changed: 286 additions & 70 deletions

File tree

‎apps/server/src/ws.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,74 @@ it.live.each(["thread", "shell"] as const)(
303303
}).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
304304
);
305305

306+
it.effect("coalesces streaming replay before synchronization and the live tail", () =>
307+
Effect.gen(function* () {
308+
const store = yield* OrchestrationEventStore.OrchestrationEventStore;
309+
const sql = yield* SqlClient.SqlClient;
310+
const threadId = ThreadId.make("thread:streaming-replay");
311+
const now = "2026-10-27T00:00:00.000Z";
312+
const insert = (version: number, text: string, streaming: boolean) => sql<{
313+
sequence: number;
314+
}>`
315+
INSERT INTO orchestration_events (
316+
event_id, aggregate_kind, stream_id, stream_version, event_type,
317+
occurred_at, actor_kind, payload_json, metadata_json, application_event_version
318+
) VALUES (
319+
${`streaming-replay:${version}`}, 'thread', ${threadId}, ${version}, 'message.updated',
320+
${now}, 'server', ${JSON.stringify({
321+
createdBy: "agent",
322+
creationSource: "web",
323+
id: "message:streaming-replay",
324+
threadId,
325+
runId: null,
326+
nodeId: null,
327+
role: "assistant",
328+
text,
329+
attachments: [],
330+
streaming,
331+
createdAt: now,
332+
updatedAt: now,
333+
})}, '{}', 2
334+
) RETURNING sequence
335+
`;
336+
yield* insert(0, "H", true);
337+
yield* insert(1, "He", true);
338+
const [latest] = yield* insert(2, "Hello", true);
339+
const [completed] = yield* insert(3, "Hello!", false);
340+
const items = yield* subscribeOrchestrationV2Thread({
341+
threadId,
342+
afterSequence: 0,
343+
requestCompletionMarker: true,
344+
}).pipe(
345+
Effect.flatMap(Stream.runCollect),
346+
Effect.provideService(ThreadManagement.ThreadManagementService, {
347+
ensureLegacyTranscript: () => Effect.void,
348+
streamStoredEventsFrom: () =>
349+
Stream.unwrap(
350+
insert(4, "Next", false).pipe(
351+
Effect.map(() =>
352+
store.readAgentEvents({ threadId, afterSequence: completed!.sequence }),
353+
),
354+
),
355+
),
356+
} as unknown as ThreadManagement.ThreadManagementService["Service"]),
357+
);
358+
assert.deepEqual(
359+
items.map((item) =>
360+
item.kind === "event"
361+
? [item.sequence, item.event.type === "message.updated" ? item.event.payload.text : null]
362+
: [item.kind],
363+
),
364+
[
365+
[latest!.sequence, "Hello"],
366+
[completed!.sequence, "Hello!"],
367+
["synchronized"],
368+
[completed!.sequence + 1, "Next"],
369+
],
370+
);
371+
}).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
372+
);
373+
306374
it.effect("shell snapshots omit idle children and older settled threads only on request", () =>
307375
Effect.gen(function* () {
308376
const shell = (

‎apps/server/src/ws.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,10 @@ import {
142142
type ShellApplicationEvent,
143143
} from "./orchestration-v2/ShellStream.ts";
144144
import { ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION } from "./orchestration-v2/ProjectionStore.ts";
145-
import { coalesceThreadLiveStream } from "./orchestration-v2/ThreadLiveEventCoalescer.ts";
145+
import {
146+
coalesceLiveUpdatedEvents,
147+
coalesceThreadLiveStream,
148+
} from "./orchestration-v2/ThreadLiveEventCoalescer.ts";
146149
import {
147150
buildBoundedThreadStreamSnapshot,
148151
decideThreadResume,
@@ -947,7 +950,9 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs
947950
// Retained creation events may describe deleted threads; replace replay only if a snapshot exists.
948951
if (shell !== null) return yield* snapshotThenLive();
949952
}
950-
const replay = yield* loadReplayThrough(input.afterSequence, highWater);
953+
const replay = coalesceLiveUpdatedEvents(
954+
yield* loadReplayThrough(input.afterSequence, highWater),
955+
);
951956
const plan = decideThreadResume({
952957
afterSequence: input.afterSequence,
953958
highWater,

‎packages/client-runtime/src/authorization/layer.test.ts‎

Lines changed: 124 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";
1+
import {
2+
AuthStandardClientScopes,
3+
EnvironmentId,
4+
ORCHESTRATION_PROTOCOL_VERSION,
5+
} from "@t3tools/contracts";
26
import { type RelayEnvironmentConnectResponse } from "@t3tools/contracts/relay";
37
import { describe, expect, it } from "@effect/vitest";
48
import * as Deferred from "effect/Deferred";
@@ -15,6 +19,11 @@ import * as RpcHttp from "../rpc/http.ts";
1519
import * as ClientCapabilities from "../platform/capabilities.ts";
1620
import * as RemoteEnvironmentAuthorization from "./service.ts";
1721
import * as TokenStore from "./tokenStore.ts";
22+
import { BearerConnectionCredential, BearerConnectionProfile } from "../connection/catalog.ts";
23+
import * as ConnectionCredentialStore from "../connection/credentialStore.ts";
24+
import { BearerConnectionTarget } from "../connection/model.ts";
25+
import * as ConnectionProfileStore from "../connection/profileStore.ts";
26+
import * as ConnectionResolver from "../connection/resolver.ts";
1827

1928
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
2029
const ENDPOINT = {
@@ -186,7 +195,7 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
186195
resetTokenCache: Effect.void,
187196
});
188197
const layer = RemoteEnvironmentAuthorization.layer.pipe(
189-
Layer.provide(
198+
Layer.provideMerge(
190199
Layer.mergeAll(
191200
RpcHttp.layerRemoteHttpClient(fetch.fetchFn),
192201
Layer.succeed(ManagedRelay.ManagedRelayDpopSigner, signer),
@@ -225,13 +234,124 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (
225234
};
226235
});
227236

237+
const prepareDirectBearer = Effect.fn("TestRemoteAuthorization.prepareDirectBearer")(function* (
238+
harness: Effect.Success<ReturnType<typeof makeHarness>>,
239+
times: number,
240+
) {
241+
const target = new BearerConnectionTarget({
242+
environmentId: ENVIRONMENT_ID,
243+
label: DESCRIPTOR.label,
244+
connectionId: "direct-1",
245+
});
246+
const entry = {
247+
target,
248+
profile: Option.some(
249+
new BearerConnectionProfile({
250+
connectionId: target.connectionId,
251+
environmentId: ENVIRONMENT_ID,
252+
label: target.label,
253+
httpBaseUrl: ENDPOINT.httpBaseUrl,
254+
wsBaseUrl: ENDPOINT.wsBaseUrl,
255+
}),
256+
),
257+
enabled: true,
258+
};
259+
const unused = () => Effect.die("unused");
260+
const layer = ConnectionResolver.layer.pipe(
261+
Layer.provide(
262+
Layer.mergeAll(
263+
harness.layer,
264+
Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, {
265+
get: unused,
266+
put: unused,
267+
remove: unused,
268+
}),
269+
Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, {
270+
get: () => Effect.succeedSome(new BearerConnectionCredential({ token: "bearer-token" })),
271+
put: unused,
272+
remove: unused,
273+
}),
274+
Layer.succeed(ClientCapabilities.PrimaryEnvironmentAuth, {
275+
bearerToken: Effect.succeedNone,
276+
}),
277+
Layer.succeed(ClientCapabilities.SshEnvironmentGateway, {
278+
provision: unused,
279+
prepare: unused,
280+
disconnect: unused,
281+
}),
282+
),
283+
),
284+
);
285+
const resolver = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layer));
286+
return yield* Effect.forEach(Array.from({ length: times }), () =>
287+
resolver.prepare(entry).pipe(Effect.result),
288+
);
289+
});
290+
228291
describe("RemoteEnvironmentAuthorization", () => {
229-
it.effect("reuses a validated bearer descriptor while issuing fresh websocket tickets", () =>
292+
it.effect("prepares a cold direct bearer connection with one descriptor request", () =>
293+
Effect.gen(function* () {
294+
const harness = yield* makeHarness({
295+
responses: [
296+
Response.json({
297+
...DESCRIPTOR,
298+
orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
299+
}),
300+
websocketTicket("cold-ticket"),
301+
],
302+
});
303+
304+
const [prepared] = yield* prepareDirectBearer(harness, 1);
305+
306+
expect(prepared).toMatchObject({
307+
_tag: "Success",
308+
success: { socketUrl: expect.stringContaining("wsTicket=cold-ticket") },
309+
});
310+
expect(harness.fetch.calls.map(([url]) => new URL(String(url)).pathname)).toEqual([
311+
"/.well-known/t3/environment",
312+
"/api/auth/websocket-ticket/rpc",
313+
]);
314+
}),
315+
);
316+
317+
it.effect("blocks a warm direct bearer prepare when the environment changes identity", () =>
318+
Effect.gen(function* () {
319+
const harness = yield* makeHarness({
320+
responses: [
321+
Response.json({
322+
...DESCRIPTOR,
323+
orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
324+
}),
325+
websocketTicket("first-ticket"),
326+
Response.json({
327+
...DESCRIPTOR,
328+
environmentId: "another-environment",
329+
orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
330+
}),
331+
],
332+
});
333+
334+
const [first, second] = yield* prepareDirectBearer(harness, 2);
335+
336+
expect(first?._tag).toBe("Success");
337+
expect(second).toMatchObject({
338+
_tag: "Failure",
339+
failure: { _tag: "ConnectionBlockedError", reason: "configuration" },
340+
});
341+
expect(
342+
harness.fetch.calls.filter(([url]) =>
343+
String(url).endsWith("/api/auth/websocket-ticket/rpc"),
344+
),
345+
).toHaveLength(1);
346+
}),
347+
);
348+
it.effect("validates a fresh bearer descriptor while issuing fresh websocket tickets", () =>
230349
Effect.gen(function* () {
231350
const harness = yield* makeHarness({
232351
responses: [
233352
Response.json(DESCRIPTOR),
234353
websocketTicket("first-ticket"),
354+
Response.json(DESCRIPTOR),
235355
websocketTicket("second-ticket"),
236356
],
237357
});
@@ -253,7 +373,7 @@ describe("RemoteEnvironmentAuthorization", () => {
253373
expect(second.socketUrl).toContain("wsTicket=second-ticket");
254374
expect(
255375
harness.fetch.calls.filter(([url]) => String(url).endsWith("/.well-known/t3/environment")),
256-
).toHaveLength(1);
376+
).toHaveLength(2);
257377
expect(
258378
harness.fetch.calls.filter(([url]) =>
259379
String(url).endsWith("/api/auth/websocket-ticket/rpc"),

‎packages/client-runtime/src/authorization/service.ts‎

Lines changed: 14 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ import * as Effect from "effect/Effect";
3333
import * as Fiber from "effect/Fiber";
3434
import * as Layer from "effect/Layer";
3535
import * as Option from "effect/Option";
36-
import * as Ref from "effect/Ref";
3736
import * as Result from "effect/Result";
3837
import * as Scope from "effect/Scope";
3938
import * as Semaphore from "effect/Semaphore";
@@ -50,6 +49,7 @@ export interface AuthorizedRemoteEnvironment {
5049
readonly httpBaseUrl: string;
5150
readonly socketUrl: string;
5251
readonly httpAuthorization: PreparedHttpAuthorization;
52+
readonly descriptor?: ExecutionEnvironmentDescriptor;
5353
}
5454

5555
export interface AuthorizedRemoteHttpEnvironment {
@@ -86,7 +86,6 @@ export class RemoteEnvironmentAuthorization extends Context.Service<
8686
>()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}
8787

8888
const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000;
89-
const BEARER_DESCRIPTOR_CACHE_TTL_MS = 10_000;
9089
const DPOP_AUTHORIZATION_TIMEOUT_MS = 30_000;
9190

9291
function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) {
@@ -127,16 +126,6 @@ export const make = Effect.gen(function* () {
127126
readonly token: Effect.Effect<TokenStore.RemoteDpopAccessToken, ConnectionAttemptError>;
128127
}
129128
>();
130-
const bearerDescriptors = yield* Ref.make<
131-
ReadonlyMap<
132-
EnvironmentId,
133-
{
134-
readonly httpBaseUrl: string;
135-
readonly descriptor: ExecutionEnvironmentDescriptor;
136-
readonly validatedAtEpochMs: number;
137-
}
138-
>
139-
>(new Map());
140129

141130
/**
142131
* A saved LAN address can belong to another machine on a different network.
@@ -147,33 +136,15 @@ export const make = Effect.gen(function* () {
147136
readonly httpBaseUrl: string;
148137
readonly connectionMethod: ClientConnectionMethod;
149138
}) {
150-
const now = yield* Clock.currentTimeMillis;
151-
const cachedDescriptor = (yield* Ref.get(bearerDescriptors)).get(input.expectedEnvironmentId);
152-
const canReuseDescriptor =
153-
cachedDescriptor?.httpBaseUrl === input.httpBaseUrl &&
154-
cachedDescriptor.validatedAtEpochMs + BEARER_DESCRIPTOR_CACHE_TTL_MS > now;
155-
const descriptor = canReuseDescriptor
156-
? cachedDescriptor.descriptor
157-
: yield* fetchDescriptor(input.httpBaseUrl, input.connectionMethod).pipe(
158-
Effect.provideService(HttpClient.HttpClient, httpClient),
159-
);
139+
const descriptor = yield* fetchDescriptor(input.httpBaseUrl, input.connectionMethod).pipe(
140+
Effect.provideService(HttpClient.HttpClient, httpClient),
141+
);
160142
if (descriptor.environmentId !== input.expectedEnvironmentId) {
161143
return yield* environmentMismatchError({
162144
expected: input.expectedEnvironmentId,
163145
actual: descriptor.environmentId,
164146
});
165147
}
166-
if (!canReuseDescriptor) {
167-
yield* Ref.update(bearerDescriptors, (current) => {
168-
const next = new Map(current);
169-
next.set(input.expectedEnvironmentId, {
170-
httpBaseUrl: input.httpBaseUrl,
171-
descriptor,
172-
validatedAtEpochMs: now,
173-
});
174-
return next;
175-
});
176-
}
177148
return descriptor;
178149
},
179150
);
@@ -204,6 +175,7 @@ export const make = Effect.gen(function* () {
204175
label: descriptor.label,
205176
httpBaseUrl: input.httpBaseUrl,
206177
socketUrl,
178+
descriptor,
207179
httpAuthorization: {
208180
_tag: "Bearer" as const,
209181
token: input.bearerToken,
@@ -492,16 +464,18 @@ export const make = Effect.gen(function* () {
492464
input: Parameters<RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]>[0],
493465
) {
494466
const endpoint = input.directEndpoint;
495-
if (endpoint !== undefined) {
496-
yield* verifyDirectEndpoint({
497-
expectedEnvironmentId: input.expectedEnvironmentId,
498-
httpBaseUrl: endpoint.httpBaseUrl,
499-
connectionMethod: "direct",
500-
});
501-
}
467+
const descriptor =
468+
endpoint === undefined
469+
? undefined
470+
: yield* verifyDirectEndpoint({
471+
expectedEnvironmentId: input.expectedEnvironmentId,
472+
httpBaseUrl: endpoint.httpBaseUrl,
473+
connectionMethod: "direct",
474+
});
502475
const authorized = (token: TokenStore.RemoteDpopAccessToken, socketUrl: string) => ({
503476
...httpAuthorization(token, endpoint?.httpBaseUrl),
504477
socketUrl,
478+
...(descriptor === undefined ? {} : { descriptor }),
505479
});
506480
let selected = yield* getDpopToken(input);
507481
if (selected.fromCache) {

0 commit comments

Comments
 (0)