Skip to content

Commit 62b71ff

Browse files
committed
refactor(gateway): retire the legacy numeric ChatAbortMarker and dead registry surface
Abort markers are process-local in-memory state (nothing persists them), so the numeric ChatAbortMarker variant — in-process rollout compat for #91013 — has been unreachable in production since every producer moved to createChatAbortMarker. Deleting it also kills the registeredAtMs timestamp fallback in isChatAbortMarkerCurrent, which makes ChatRunEntry.registeredAtMs entirely write-only; the sequence comparison is the sole ordering authority. Dead surface riders (same owner file): - ChatRunRegistry.clear had zero callers (restart teardown clears through chatRunState.clear, which owns the whole store). - createChatRunRegistry/createToolEventRecipientRegistry standalone factories were consumed only by tests; production always goes through createChatRunState. Tests now use the state-owned instances, and the server-chat barrel re-exports are gone. Net -32 production LOC; 462 tests across the five touched suites green.
1 parent 3ec4089 commit 62b71ff

7 files changed

Lines changed: 25 additions & 55 deletions

‎src/gateway/gateway-misc.test.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,7 @@ import {
2727
resolveNodeCommandAllowlist,
2828
} from "./node-command-policy.js";
2929
import { createGatewayBroadcaster } from "./server-broadcast.js";
30-
import { createSessionMessageSubscriberRegistry } from "./server-chat-state.js";
31-
import { createChatRunRegistry } from "./server-chat.js";
30+
import { createChatRunState, createSessionMessageSubscriberRegistry } from "./server-chat-state.js";
3231
import { MAX_BUFFERED_BYTES } from "./server-constants.js";
3332
import { handleNodeInvokeResult } from "./server-methods/nodes.handlers.invoke-result.js";
3433
import type { GatewayClient as GatewayMethodClient } from "./server-methods/types.js";
@@ -916,7 +915,7 @@ describe("gateway broadcaster", () => {
916915

917916
describe("chat run registry", () => {
918917
test("queues and removes runs per session", () => {
919-
const registry = createChatRunRegistry();
918+
const registry = createChatRunState().registry;
920919

921920
registry.add("s1", { sessionKey: "main", clientRunId: "c1" });
922921
registry.add("s1", { sessionKey: "main", clientRunId: "c2" });

‎src/gateway/server-chat-state.ts‎

Lines changed: 8 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,10 @@ export type ChatRunRegistration = {
2525
};
2626

2727
export type ChatRunEntry = ChatRunRegistration & {
28-
registeredAtMs: number;
2928
registeredSequence: number;
3029
};
3130

32-
export type ChatAbortMarker = number | { abortedAtMs: number; sequence: number };
31+
export type ChatAbortMarker = { abortedAtMs: number; sequence: number };
3332

3433
let chatRunOrderingSequence = 0;
3534

@@ -42,7 +41,6 @@ function nextChatRunOrderingSequence(): number {
4241
function createChatRunEntry(entry: ChatRunRegistration): ChatRunEntry {
4342
return {
4443
...entry,
45-
registeredAtMs: Date.now(),
4644
registeredSequence: nextChatRunOrderingSequence(),
4745
};
4846
}
@@ -52,34 +50,24 @@ export function createChatAbortMarker(now = Date.now()): ChatAbortMarker {
5250
return { abortedAtMs: now, sequence: nextChatRunOrderingSequence() };
5351
}
5452

55-
/** Return the wall-clock timestamp used by maintenance TTL pruning for both legacy and structured markers. */
53+
/** Return the wall-clock timestamp used by maintenance TTL pruning. */
5654
export function chatAbortMarkerTimestampMs(marker: ChatAbortMarker): number {
57-
return typeof marker === "number" ? marker : marker.abortedAtMs;
55+
return marker.abortedAtMs;
5856
}
5957

6058
/**
6159
* Return whether an abort marker should suppress events for the given chat run registration.
62-
* Structured markers compare the monotonic sequence first so same-millisecond aborts stay ordered;
63-
* legacy numeric markers fall back to timestamp comparison, and a missing entry preserves old suppress-on-presence behavior.
60+
* The shared monotonic sequence keeps same-millisecond aborts ordered; a missing
61+
* entry preserves suppress-on-presence behavior.
6462
*/
6563
export function isChatAbortMarkerCurrent(
6664
marker: ChatAbortMarker | undefined,
67-
entry?: Pick<ChatRunEntry, "registeredAtMs" | "registeredSequence">,
65+
entry?: Pick<ChatRunEntry, "registeredSequence">,
6866
): boolean {
6967
if (marker === undefined) {
7068
return false;
7169
}
72-
if (!entry) {
73-
return true;
74-
}
75-
if (typeof marker !== "number" && typeof entry.registeredSequence === "number") {
76-
return marker.sequence >= entry.registeredSequence;
77-
}
78-
if (typeof entry.registeredAtMs !== "number") {
79-
return true;
80-
}
81-
const abortedAtMs = typeof marker === "number" ? marker : marker.abortedAtMs;
82-
return abortedAtMs >= entry.registeredAtMs;
70+
return !entry || marker.sequence >= entry.registeredSequence;
8371
}
8472

8573
export type BufferedAgentEvent = {
@@ -180,7 +168,6 @@ export type ChatRunRegistry = {
180168
peek: (sessionId: string) => ChatRunEntry | undefined;
181169
shift: (sessionId: string) => ChatRunEntry | undefined;
182170
remove: (sessionId: string, clientRunId: string, sessionKey?: string) => ChatRunEntry | undefined;
183-
clear: () => void;
184171
};
185172

186173
function createChatRunRegistryForStore(store: ChatRunRecordStore): ChatRunRegistry {
@@ -238,19 +225,7 @@ function createChatRunRegistryForStore(store: ChatRunRecordStore): ChatRunRegist
238225
return entry;
239226
};
240227

241-
const clear = () => {
242-
for (const [runId, record] of store.runs) {
243-
delete record.registrations;
244-
store.releaseIfEmpty(runId);
245-
}
246-
};
247-
248-
return { add, peek, shift, remove, clear };
249-
}
250-
251-
/** Create the FIFO registry that maps session IDs to active chat runs. */
252-
export function createChatRunRegistry(): ChatRunRegistry {
253-
return createChatRunRegistryForStore(createChatRunRecordStore());
228+
return { add, peek, shift, remove };
254229
}
255230

256231
export type ChatRunState = {
@@ -756,8 +731,3 @@ function createToolEventRecipientRegistryForStore(
756731

757732
return { add, get, markFinal };
758733
}
759-
760-
/** Create the run-id recipient registry used for streaming tool events. */
761-
export function createToolEventRecipientRegistry(): ToolEventRecipientRegistry {
762-
return createToolEventRecipientRegistryForStore(createChatRunRecordStore());
763-
}

‎src/gateway/server-chat.agent-events.test.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,6 @@ import {
9494
createSessionEventSubscriberRegistry,
9595
createChatAbortMarker,
9696
createSessionMessageSubscriberRegistry,
97-
createToolEventRecipientRegistry,
9897
resolveChatErrorKindFromError,
9998
type AgentEventHandlerOptions,
10099
} from "./server-chat.js";
@@ -169,7 +168,7 @@ describe("agent event handler", () => {
169168
vi.fn<NonNullable<AgentEventHandlerOptions["clearTrackedActiveRun"]>>();
170169
const agentRunSeq = new Map<string, number>();
171170
const chatRunState = createChatRunState();
172-
const toolEventRecipients = createToolEventRecipientRegistry();
171+
const toolEventRecipients = chatRunState.toolEventRecipients;
173172
const sessionEventSubscribers = createSessionEventSubscriberRegistry();
174173
const sessionMessageSubscribers = createSessionMessageSubscriberRegistry();
175174

@@ -3289,8 +3288,8 @@ describe("agent event handler", () => {
32893288

32903289
it.each([
32913290
{
3292-
name: "older timestamp",
3293-
marker: () => 1_000,
3291+
name: "older sequence",
3292+
marker: () => ({ abortedAtMs: 1_000, sequence: -2 }),
32943293
},
32953294
{
32963295
name: "same-millisecond older sequence",
@@ -4422,7 +4421,8 @@ describe("agent event handler", () => {
44224421
isControlUiVisible: false,
44234422
verboseLevel: "off",
44244423
});
4425-
chatRunState.getOrCreate("run-hidden-commentary-aborted").abortMarker = 1_000;
4424+
chatRunState.getOrCreate("run-hidden-commentary-aborted").abortMarker =
4425+
createChatAbortMarker(1_000);
44264426

44274427
emitAgentEvent(handler, "run-hidden-commentary-aborted", "assistant", {
44284428
text: "This aborted commentary must not be mirrored.",

‎src/gateway/server-chat.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,9 @@ import { formatForLog } from "./ws-log.js";
6868

6969
export {
7070
createChatAbortMarker,
71-
createChatRunRegistry,
7271
createChatRunState,
7372
createSessionEventSubscriberRegistry,
7473
createSessionMessageSubscriberRegistry,
75-
createToolEventRecipientRegistry,
7674
} from "./server-chat-state.js";
7775
export type {
7876
ChatAbortMarker,

‎src/gateway/server-maintenance.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { HealthSummary } from "./health/types.js";
66
const CURATOR_INITIAL_DELAY_MS = 5 * 60_000;
77
const CURATOR_SWEEP_INTERVAL_MS = 24 * 60 * 60_000;
88
import type { ChatAbortControllerEntry } from "./chat-abort.js";
9+
import { createChatAbortMarker } from "./server-chat-state.js";
910
import { DEDUPE_MAX, DEDUPE_TTL_MS } from "./server-constants.js";
1011
import { pendingChatSendDedupeKey } from "./server-shared.js";
1112
import { createGatewayMaintenanceStateForTest } from "./test-helpers.maintenance-state.js";
@@ -792,7 +793,7 @@ describe("startGatewayMaintenanceTimers", () => {
792793
const { startGatewayMaintenanceTimers } = await import("./server-maintenance.js");
793794
const deps = createMaintenanceTimerDeps();
794795
const runId = "run-aborted";
795-
deps.chatRunState.getOrCreate(runId).abortMarker = staleRunTimestamp();
796+
deps.chatRunState.getOrCreate(runId).abortMarker = createChatAbortMarker(staleRunTimestamp());
796797
seedStaleRunBuffers(deps, runId);
797798
seedBufferedAgentEvent(deps, runId);
798799
const agentText = deps.chatRunState.getOrCreate(runId).agentText?.assistant;

‎src/gateway/server-methods/server-methods.test.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ import {
3939
} from "../chat-display-projection.js";
4040
import { ExecApprovalManager } from "../exec-approval-manager.js";
4141
import type { HealthSummary } from "../health/types.js";
42-
import { createChatRunState } from "../server-chat-state.js";
42+
import { createChatAbortMarker, createChatRunState } from "../server-chat-state.js";
4343
import { HEALTH_REFRESH_INTERVAL_MS } from "../server-constants.js";
4444
import { injectTimestamp, timestampOptsFromConfig } from "./agent-timestamp.js";
4545
import { normalizeRpcAttachmentsToChatAttachments } from "./attachment-normalize.js";
@@ -2891,7 +2891,7 @@ describe("exec approval handlers", () => {
28912891

28922892
it("rejects approval registration after the owning run was aborted", async () => {
28932893
const { manager, handlers, broadcasts, respond, context } = createExecApprovalFixture();
2894-
context.chatRunState.getOrCreate("run-aborted").abortMarker = Date.now();
2894+
context.chatRunState.getOrCreate("run-aborted").abortMarker = createChatAbortMarker();
28952895

28962896
await requestExecApproval({
28972897
handlers,
@@ -2941,7 +2941,8 @@ describe("exec approval handlers", () => {
29412941
"approval-allowed-before-abort",
29422942
);
29432943
expect(manager.resolve("approval-allowed-before-abort", "allow-once")).toBe(true);
2944-
context.chatRunState.getOrCreate("run-allowed-before-abort").abortMarker = Date.now();
2944+
context.chatRunState.getOrCreate("run-allowed-before-abort").abortMarker =
2945+
createChatAbortMarker();
29452946
await requestPromise;
29462947

29472948
const waitRespond = vi.fn();

‎src/gateway/server-runtime-subscriptions.test.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ import {
3333
createChatRunState,
3434
createSessionEventSubscriberRegistry,
3535
createSessionMessageSubscriberRegistry,
36-
createToolEventRecipientRegistry,
3736
} from "./server-chat-state.js";
3837
import type { TaskEventPayload } from "./server-methods/task-summary.js";
3938
import { TerminalSessionManager } from "./terminal/session-manager.js";
@@ -163,8 +162,10 @@ function createParams(): SubscriptionParams {
163162
broadcastToConnIds: vi.fn(),
164163
nodeSendToSession: vi.fn(),
165164
agentRunSeq: new Map(),
166-
chatRunState: createChatRunState(),
167-
toolEventRecipients: createToolEventRecipientRegistry(),
165+
...(() => {
166+
const chatRunState = createChatRunState();
167+
return { chatRunState, toolEventRecipients: chatRunState.toolEventRecipients };
168+
})(),
168169
sessionEventSubscribers: createSessionEventSubscriberRegistry(),
169170
sessionMessageSubscribers: createSessionMessageSubscriberRegistry(),
170171
chatAbortControllers: new Map(),

0 commit comments

Comments
 (0)