@myclaw163/clawclaw-cli 0.8.17 → 0.8.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -67,6 +67,31 @@ Channel server 终止只会断开 transport。它不停止 Owner,不取消当
67
67
 
68
68
  ## 可观测性
69
69
 
70
+ ### GameSync 收包隔离与超时复盘
71
+
72
+ Owner 的 GameSync WS、序号校验、delta 还原、ping/pong 和原始收包记录运行在 Source 所属的独立 Worker。Runtime 协调线程接纳完整 State 后异步调度已有插件图;心跳不等待感知/Behavior计算。短命令不创建这个 Worker。
73
+
74
+ Scheduler 每次重新调度会让出一个事件循环轮次,给待处理的传输/Worker消息进入Source的机会,避免连续微任务一直先执行计算。插件依赖、顺序提交、关键epoch保护和计算并发上限保持原有语义;不会承诺资源耗尽时无限吞吐。
75
+
76
+ Worker 到 Source 的未确认完整帧默认最多10个,编码字节预算8MiB。收到消息或进入Owner回调都不代表 Source 已接纳:只有现有 `acknowledgeGameSync` 边界推进可恢复基线。原始 delta 不被跳过;计算层仍使用自己的有界追赶策略。入口超出预算时显式记录 `CCL_INGRESS_BACKLOG_LIMIT`(本地1013),停止该连接并在接纳完成后从已接受序号恢复。恢复窗口不足时仍需snapshot fallback并记录缺口,不能承诺服务器已关闭后补回全部历史。
77
+
78
+ 生产级复盘使用 `CLAWCLAW_OBSERVABILITY_LEVEL=full`,在Owner启动前设置。需要确认日志出现以下记录;仅看CLI版本号或导出目录名不能证明新实现已运行:
79
+
80
+ | 记录 | 关键字段和含义 |
81
+ | --- | --- |
82
+ | `runtime.ws.ingress_window` | 每5秒的Worker计数快照;`implementation=isolated_gamesync_v1`、package/Node版本、transport_generation、thread_id;接收/Source接受/ACK提交序号;未接受帧数与字节、过载次数;ping接收与pong写入计数、最近时间、最大写入延迟、Worker事件循环延迟 |
83
+ | `runtime.source.frame_admitted` | 每个接纳帧的epoch_seq/source_seq/domain_tick;socket接收、decode完成、Worker发出、Owner收到、Source开始和接纳完成的本机时间;decode、跨线程交付、Source排队和接纳耗时 |
84
+ | `runtime.view.ready` | 同epoch的intake/scheduler/finalize/total时间,以及`received_to_ready_ms`;full级别保留这条记录,不再视作数据库重复项过滤 |
85
+ | `runtime.diagnostics.sample` | Owner进程内存/保留记录数、CPU增量、事件循环利用率和延迟、GC次数/时间、各计算池状态 |
86
+ | `runtime.ws.ingress_disconnected` / `runtime.ws.ingress_failed` | 区分后端关闭、入口过载、Worker启动失败/崩溃;附transport_generation,避免不同连接混算 |
87
+ | `runtime.ws.ingress_stop_timeout` | Worker或原始日志未在5秒内收尾,执行有界终止;不能冒充正常日志排空 |
88
+
89
+ 按epoch_seq连接`frame_admitted`和`view.ready`;按transport_generation关联收包、心跳和重连窗口。Worker原始日志的ts在接收线程内产生,因此Owner主线程阻塞时仍保留原始接收时间。入口收到时仍是JS回调边界,不是内核网卡收包时刻,也不是后端生产时间。
90
+
91
+ `written_pong_count`和`last_pong_written_at_ms`表示本地socket写入回调完成,不能冒充服务端收到。`ack_submitted_seq`也只表示本地提交ACK;需要服务端日志才能确认对端时刻。进程CPU增量包含Worker线程;Owner和收包Worker的事件循环延迟分别查看。
92
+
93
+ 原始日志沿用既有容量滚动设置,由Worker异步写入;结束后Owner等待Worker关闭并汇总raw日志统计,再关闭诊断输出。Worker到Owner的周期诊断只允许一个尚未被Owner确认的快照,阻塞期间累计数字,不无限积压诊断消息。
94
+
70
95
  结构化诊断写入账号 runtime 目录,不混入 Agent Event:
71
96
 
72
97
  | 层 | 关键诊断 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.8.17",
3
+ "version": "0.8.18",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -12,6 +12,7 @@ import {
12
12
  type GameSyncResumeState,
13
13
  } from '../runtime/ws-client.js';
14
14
  import { RuntimeLogger } from '../runtime/runtime-logger.js';
15
+ import { ThreadedWsClient, type ThreadedWsClientConfig } from '../runtime/threaded-ws-client.js';
15
16
  import type { RawWsMessageSink } from '../runtime/raw-ws-log.js';
16
17
  import type { GameSyncPerceptionReport } from '../runtime/game-sync-protocol.js';
17
18
  import type { QueueMode } from './competition.js';
@@ -36,6 +37,8 @@ export interface GameClientConfig {
36
37
  rawWsMessageSink?: RawWsMessageSink;
37
38
  /** Cancels owner-scoped HTTP work before Action authority is released. */
38
39
  signal?: AbortSignal;
40
+ /** Owner-only Source transport isolation. Ephemeral clients do not start an ingress Worker. */
41
+ gameSyncIngress?: Omit<ThreadedWsClientConfig, 'url' | 'apiKey' | 'resumeState'>;
39
42
  }
40
43
 
41
44
  export interface GameServerDiscoveryResult {
@@ -69,7 +72,10 @@ function agentMetadataHeaders(options: RoomEntryMetadata): Record<string, string
69
72
 
70
73
  export class GameClient {
71
74
  private http: HttpTransport;
72
- private ws: WsClient | null = null;
75
+ private ws: Pick<WsClient, keyof WsClient> | null = null;
76
+ private readonly gameSyncIngress?: GameClientConfig['gameSyncIngress'];
77
+ private readonly closingIngress = new Set<Promise<void>>();
78
+ private transportGeneration = 0;
73
79
  /** Last continuously reduced v2 baseline, retained across failed socket replacements. */
74
80
  private gameSyncResumeState?: GameSyncResumeState;
75
81
  /** Queue/room-owned game identity that the retained baseline must belong to. */
@@ -111,6 +117,7 @@ export class GameClient {
111
117
  this.apiKey = config.apiKey;
112
118
  this.enableWs = config.enableWs ?? false;
113
119
  this.rawWsMessageSink = config.rawWsMessageSink;
120
+ this.gameSyncIngress = config.gameSyncIngress;
114
121
  this.registry = new ServerRegistry({
115
122
  lobbyUrl: config.lobbyUrl,
116
123
  gameServerUrl: config.gameServerUrl,
@@ -196,8 +203,8 @@ export class GameClient {
196
203
  }
197
204
 
198
205
  /** Irreversible confirmed Action endpoint; input must already be prepared. */
199
- async submitPreparedActionConfirmed(action: GameActionRequest): Promise<TransportResponse> {
200
- return this.http.postRaw('/api/v1/game/action', action);
206
+ async submitPreparedActionConfirmed(action: GameActionRequest, signal?: AbortSignal): Promise<TransportResponse> {
207
+ return this.http.postRaw('/api/v1/game/action', action, undefined, signal);
201
208
  }
202
209
 
203
210
  private async prepareAction(action: GameActionRequest): Promise<GameActionRequest> {
@@ -469,11 +476,11 @@ export class GameClient {
469
476
  if (resumeState) this.gameSyncResumeState = resumeState;
470
477
  if (this.ws) {
471
478
  this.ws.clearHandlers();
472
- this.ws.disconnect();
479
+ await this.stopWs(this.ws);
473
480
  this.markWsHandlersDetached();
474
481
  }
475
482
 
476
- const newWs = new WsClient({
483
+ const newWs = this.createWs({
477
484
  url: wsUrl,
478
485
  apiKey: this.apiKey,
479
486
  rawMessageSink: this.rawWsMessageSink,
@@ -487,7 +494,7 @@ export class GameClient {
487
494
  } catch {
488
495
  this.rememberGameSyncResumeState(newWs.resumeState);
489
496
  this.log.warn('WS_CONNECT', 'GameSync WebSocket connection failed; runtime will retry');
490
- newWs.disconnect();
497
+ await this.stopWs(newWs);
491
498
  this.ws = null;
492
499
  this.markWsHandlersDetached();
493
500
  return false;
@@ -500,7 +507,7 @@ export class GameClient {
500
507
  this.rememberGameSyncResumeState(this.ws?.resumeState);
501
508
  }
502
509
  if (this.ws) {
503
- this.ws.disconnect();
510
+ this.stopWs(this.ws);
504
511
  this.ws = null;
505
512
  }
506
513
  if (!options.preserveGameSyncResumeState) {
@@ -559,11 +566,11 @@ export class GameClient {
559
566
  if (resumeState) this.gameSyncResumeState = resumeState;
560
567
  if (this.ws) {
561
568
  this.ws.clearHandlers();
562
- this.ws.disconnect();
569
+ await this.stopWs(this.ws);
563
570
  this.markWsHandlersDetached();
564
571
  }
565
572
 
566
- const newWs = new WsClient({
573
+ const newWs = this.createWs({
567
574
  url: wsUrl,
568
575
  apiKey: this.apiKey,
569
576
  rawMessageSink: this.rawWsMessageSink,
@@ -577,7 +584,7 @@ export class GameClient {
577
584
  } catch {
578
585
  this.rememberGameSyncResumeState(newWs.resumeState);
579
586
  this.log.warn('WS_RECONNECT', 'GameSync WebSocket reconnect failed; runtime will retry');
580
- newWs.disconnect();
587
+ await this.stopWs(newWs);
581
588
  this.ws = null;
582
589
  this.markWsHandlersDetached();
583
590
  }
@@ -700,6 +707,29 @@ export class GameClient {
700
707
  for (const entry of this.wsRecoveryStartedHandlers) entry.unsubscribe = undefined;
701
708
  }
702
709
 
710
+ private createWs(config: ConstructorParameters<typeof WsClient>[0]): Pick<WsClient, keyof WsClient> {
711
+ if (!this.gameSyncIngress) return new WsClient(config);
712
+ const { rawMessageSink: _sink, ...options } = config;
713
+ return new ThreadedWsClient({ ...options, ...this.gameSyncIngress, transportGeneration: ++this.transportGeneration });
714
+ }
715
+
716
+ private stopWs(ws: Pick<WsClient, keyof WsClient>): Promise<void> {
717
+ ws.disconnect();
718
+ if (ws instanceof ThreadedWsClient) {
719
+ const closing = ws.close();
720
+ this.closingIngress.add(closing);
721
+ void closing.finally(() => this.closingIngress.delete(closing));
722
+ return closing;
723
+ }
724
+ return Promise.resolve();
725
+ }
726
+
727
+ /** Drain Source-owned ingress and raw journals before Owner telemetry closes. */
728
+ async closeGameSyncTransports(): Promise<void> {
729
+ this.disconnectWs();
730
+ await Promise.allSettled([...this.closingIngress]);
731
+ }
732
+
703
733
  private rememberGameSyncResumeState(candidate: GameSyncResumeState | undefined): void {
704
734
  if (!candidate) return;
705
735
  const expected = this.expectedGameSyncGameId;
@@ -135,8 +135,8 @@ export class HttpTransport {
135
135
  }
136
136
  }
137
137
 
138
- async postRaw(path: string, body?: any, perRequestHeaders?: Record<string, string>): Promise<TransportResponse> {
139
- return this.requestRaw('POST', path, body, perRequestHeaders);
138
+ async postRaw(path: string, body?: any, perRequestHeaders?: Record<string, string>, requestSignal?: AbortSignal): Promise<TransportResponse> {
139
+ return this.requestRaw('POST', path, body, perRequestHeaders, requestSignal);
140
140
  }
141
141
 
142
142
  /** GET with one fast retry for transient network failures. */
@@ -11,6 +11,7 @@ import {
11
11
  } from 'node:fs';
12
12
  import { join } from 'node:path';
13
13
  import { getHeapStatistics } from 'node:v8';
14
+ import { RuntimeProcessTimingSampler } from '../observability/process-timing.js';
14
15
  import type { AuthProfile } from '../../lib/auth.js';
15
16
  import { GameClient } from '../../lib/game-client.js';
16
17
  import { getProfileRuntimeStateDir, getWorkspaceDir } from '../../lib/init-command.js';
@@ -55,7 +56,8 @@ import {
55
56
  watchParentProcess,
56
57
  type ParentProcessWatchHandle,
57
58
  } from '../parent-process-watch.js';
58
- import { BufferedRawWsLog, ownerRawWsLogPath } from '../raw-ws-log.js';
59
+ import { ownerRawWsLogPath } from '../raw-ws-log.js';
60
+ import type { ThreadedWsClientConfig } from '../threaded-ws-client.js';
59
61
  import {
60
62
  presentCanonicalEventForCclEvents,
61
63
  presentCanonicalEventForDesktop,
@@ -667,7 +669,8 @@ export async function runClawclawOwner(
667
669
  ): Promise<ClawclawSourceCompletion> {
668
670
  let lock: OwnerLock | undefined;
669
671
  let telemetry: ReturnType<typeof createOwnerTelemetryRecorder> | undefined;
670
- let rawWsLog: BufferedRawWsLog | undefined;
672
+ let ingressRawLog: ThreadedWsClientConfig['rawLog'];
673
+ let closeGameSyncTransports: (() => Promise<void>) | undefined;
671
674
  let runtime: ReturnType<typeof createClawclawRuntime> | undefined;
672
675
  let source: ClawclawSourcePlugin | undefined;
673
676
  let mailbox: ClawclawMailboxPlugin | undefined;
@@ -685,6 +688,7 @@ export async function runClawclawOwner(
685
688
  let relayPromise: Promise<void> | undefined;
686
689
  let parentWatch: ParentProcessWatchHandle | undefined;
687
690
  let diagnosticSampleTimer: ReturnType<typeof setInterval> | undefined;
691
+ let processTimingSampler: RuntimeProcessTimingSampler | undefined;
688
692
  let localStopRequested = false;
689
693
  let forceExitTimer: ReturnType<typeof setTimeout> | undefined;
690
694
  const channelPolicy = channelOwnerDeliveryPolicy(options.channelDelivery);
@@ -705,10 +709,7 @@ export async function runClawclawOwner(
705
709
  const fullDiagnosticsEnabled = resolveOwnerObservabilityLevel() === 'full';
706
710
  if (fullDiagnosticsEnabled) {
707
711
  const retention = observabilityRetention();
708
- rawWsLog = new BufferedRawWsLog(
709
- ownerRawWsLogPath(getProfileRuntimeStateDir(options.profile)),
710
- retention,
711
- );
712
+ ingressRawLog = { path: ownerRawWsLogPath(getProfileRuntimeStateDir(options.profile)), options: retention };
712
713
  telemetry.log('info', 'runtime.raw_ws.capture_started', {
713
714
  max_file_bytes: retention.maxFileBytes,
714
715
  retained_files: retention.retainedFiles,
@@ -719,8 +720,14 @@ export async function runClawclawOwner(
719
720
  apiKey: options.profile.apiKey,
720
721
  agentName: options.profile.agentName,
721
722
  enableWs: true,
722
- rawWsMessageSink: rawWsLog,
723
+ gameSyncIngress: {
724
+ rawLog: ingressRawLog,
725
+ diagnostic: (name, attributes, severity = 'debug') => telemetry?.log(severity, name, attributes, {
726
+ component: 'runtime.transport', scope: runtime?.publicScope(),
727
+ }),
728
+ },
723
729
  });
730
+ closeGameSyncTransports = () => client.closeGameSyncTransports();
724
731
  const workspaceDir = getWorkspaceDir();
725
732
  ensureAccountUserDataLayout(workspaceDir, options.profile);
726
733
  const perceptionConfig = readWorkspacePerceptionConfig();
@@ -825,6 +832,7 @@ export async function runClawclawOwner(
825
832
  behaviorEventTypes: assembly.behavior.produces?.events ?? [],
826
833
  });
827
834
  if (fullDiagnosticsEnabled) {
835
+ processTimingSampler = new RuntimeProcessTimingSampler();
828
836
  const sample = (): void => {
829
837
  try {
830
838
  const memory = process.memoryUsage();
@@ -838,6 +846,11 @@ export async function runClawclawOwner(
838
846
  : undefined;
839
847
  telemetry?.log('debug', 'runtime.diagnostics.sample', {
840
848
  sample_interval_ms: FULL_DIAGNOSTIC_SAMPLE_INTERVAL_MS,
849
+ node_version: process.version,
850
+ process_platform: process.platform,
851
+ process_arch: process.arch,
852
+ process_uptime_seconds: Math.round(process.uptime()),
853
+ process_timing: processTimingSampler?.sample(),
841
854
  process_memory: {
842
855
  rss_bytes: memory.rss,
843
856
  heap_total_bytes: memory.heapTotal,
@@ -1483,6 +1496,7 @@ export async function runClawclawOwner(
1483
1496
  return completion;
1484
1497
  } finally {
1485
1498
  if (diagnosticSampleTimer) clearInterval(diagnosticSampleTimer);
1499
+ processTimingSampler?.stop();
1486
1500
  process.off('SIGINT', onSignal);
1487
1501
  process.off('SIGTERM', onSignal);
1488
1502
  if (forceExitTimer) clearTimeout(forceExitTimer);
@@ -1499,16 +1513,7 @@ export async function runClawclawOwner(
1499
1513
  }
1500
1514
  } finally {
1501
1515
  try {
1502
- if (rawWsLog) {
1503
- await rawWsLog.close();
1504
- const stats = rawWsLog.stats();
1505
- telemetry?.log(
1506
- stats.dropped > 0 || stats.failedBatches > 0 ? 'warn' : 'info',
1507
- 'runtime.raw_ws.capture_stopped',
1508
- { ...stats },
1509
- { component: 'runtime.transport' },
1510
- );
1511
- }
1516
+ await closeGameSyncTransports?.();
1512
1517
  await telemetry?.closeWithin(2_000).catch(() => false);
1513
1518
  } finally {
1514
1519
  lock?.release();
@@ -125,6 +125,17 @@ function deferredAtCommitBoundary(
125
125
  return authority.status === 'deferred' ? authority.result : undefined;
126
126
  }
127
127
 
128
+ /** Release the Action even if preparation or a provider ignores cancellation. */
129
+ function untilAborted<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
130
+ return new Promise<T>((resolve, reject) => {
131
+ const abort = (): void => reject(signal.reason ?? new Error('ACTION_CANCELLED'));
132
+ const cleanup = (): void => signal.removeEventListener('abort', abort);
133
+ operation.then((value) => { cleanup(); resolve(value); }, (error) => { cleanup(); reject(error); });
134
+ if (signal.aborted) abort();
135
+ else signal.addEventListener('abort', abort, { once: true });
136
+ });
137
+ }
138
+
128
139
  type AutomatedActionCaller = Extract<ActionCaller, { kind: 'behavior' }>;
129
140
 
130
141
  function isAutomatedCaller(caller: ActionCaller): caller is AutomatedActionCaller {
@@ -559,12 +570,13 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
559
570
  let actionEndpointStarted = false;
560
571
  const action = { ...admitted.action };
561
572
  try {
573
+ context.signal.throwIfAborted();
562
574
  if (request.audioFile) {
563
- const uploaded = await this.client.uploadAudio(
575
+ const uploaded = await untilAborted(this.client.uploadAudio(
564
576
  request.audioFile.path,
565
577
  undefined,
566
578
  request.audioFile.contentType,
567
- );
579
+ ), context.signal);
568
580
  action.audio_url = uploaded.audio_url;
569
581
  const rejected = this.commitBoundaryRejection(
570
582
  request, scope, admitted.actionId, caller, context,
@@ -582,20 +594,35 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
582
594
  return acknowledgedActionResult(
583
595
  scope,
584
596
  admitted.actionId,
585
- await pending,
597
+ await untilAborted(pending, context.signal),
586
598
  );
587
599
  }
588
- const preparedAction = await this.client.prepareActionForConfirmedSubmission(action as any);
600
+ const preparedAction = await untilAborted(this.client.prepareActionForConfirmedSubmission(action as any), context.signal);
601
+ context.signal.throwIfAborted();
589
602
  const rejected = this.commitBoundaryRejection(
590
603
  request, scope, admitted.actionId, caller, context,
591
604
  );
592
605
  if (rejected) return rejected;
593
- const pending = this.client.submitPreparedActionConfirmed(preparedAction);
606
+ const pending = this.client.submitPreparedActionConfirmed(preparedAction, context.signal);
594
607
  actionEndpointStarted = true;
595
608
  markProviderStartedOrSkipped(true);
596
- const response = await pending;
609
+ const response = await untilAborted(pending, context.signal);
597
610
  return acknowledgedActionResult(scope, admitted.actionId, response);
598
611
  } catch (error) {
612
+ if (context.signal.aborted) {
613
+ if (!actionEndpointStarted) {
614
+ const rejected = deferredAtCommitBoundary(context);
615
+ if (rejected) return rejected;
616
+ }
617
+ const reason = context.signal.reason;
618
+ const code = reason instanceof Error && ['GAME_ENDED', 'ACTION_SCOPE_ENDED'].includes(reason.message)
619
+ ? reason.message : 'ACTION_CANCELLED';
620
+ return actionResult(scope, admitted.actionId, 'failure', undefined, {
621
+ error: { code, message: actionEndpointStarted
622
+ ? 'Action wait cancelled; the backend execution outcome is unknown.'
623
+ : 'Action cancelled before submission.' },
624
+ }, { source: 'local', actionOutcome: actionEndpointStarted ? 'unknown' : 'not_submitted' });
625
+ }
599
626
  return actionResult(scope, admitted.actionId, 'failure', undefined, backendError(error), {
600
627
  source: error instanceof ApiError ? 'backend' : 'transport',
601
628
  actionOutcome: actionEndpointStarted
@@ -833,6 +833,14 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
833
833
  }
834
834
 
835
835
  const current = this.manager.current();
836
+ if (!current) {
837
+ const stack = this.manager.snapshot();
838
+ // An empty host has no activation that will consume this batch later.
839
+ // Drain only this plugin's cursor; canonical Events remain available to
840
+ // other consumers. A suspended long waiting for hand-back still owns
841
+ // its pending Events, even though current() temporarily returns nothing.
842
+ if (!stack.long && !stack.short && !stack.reflex) return this.output(cursor);
843
+ }
836
844
  if (
837
845
  !current
838
846
  || computed.activationId !== current.activationId
@@ -1453,6 +1453,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1453
1453
  }
1454
1454
 
1455
1455
  private async acceptGameFrame(frame: WsInputFrame): Promise<ClawclawGameTransportStopReason | void> {
1456
+ const sourceStartedAtMs = Date.now();
1456
1457
  const segment = this.requireRuntime().currentSegment();
1457
1458
  if (
1458
1459
  frame.meta.origin === 'snapshot'
@@ -1659,6 +1660,24 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1659
1660
  }
1660
1661
  });
1661
1662
  if (!acceptance) return;
1663
+ const ingress = frame.meta.ingress;
1664
+ if (ingress) {
1665
+ const acceptedAtMs = Date.now();
1666
+ this.diagnostic('runtime.source.frame_admitted', {
1667
+ epoch_seq: acceptance.epoch.epochSeq, source_seq: frame.meta.sourceSeq, domain_tick: frame.meta.domainTick,
1668
+ transport_generation: ingress.transportGeneration,
1669
+ socket_received_at_ms: ingress.socketReceivedAtMs, decoded_at_ms: ingress.decodedAtMs,
1670
+ worker_posted_at_ms: ingress.workerPostedAtMs, owner_received_at_ms: ingress.ownerReceivedAtMs,
1671
+ source_started_at_ms: sourceStartedAtMs, source_accepted_at_ms: acceptedAtMs,
1672
+ decode_ms: ingress.decodeDurationMs,
1673
+ worker_handoff_ms: ingress.ownerReceivedAtMs === undefined || ingress.workerPostedAtMs === undefined
1674
+ ? undefined : Math.max(0, ingress.ownerReceivedAtMs - ingress.workerPostedAtMs),
1675
+ source_queue_ms: ingress.ownerReceivedAtMs === undefined ? undefined : Math.max(0, sourceStartedAtMs - ingress.ownerReceivedAtMs),
1676
+ source_admission_ms: Math.max(0, acceptedAtMs - sourceStartedAtMs),
1677
+ receive_to_admitted_ms: Math.max(0, acceptedAtMs - ingress.socketReceivedAtMs),
1678
+ outstanding_frames: ingress.outstandingFrames, outstanding_bytes: ingress.outstandingBytes,
1679
+ });
1680
+ }
1662
1681
  if (typeof frame.meta.sourceSeq !== 'number') {
1663
1682
  throw new TypeError('GameSync frame sourceSeq must be numeric.');
1664
1683
  }
@@ -2410,6 +2429,12 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
2410
2429
  ...(crossedActionSafetyBoundary ? { coalescing: 'forbidden' as const } : {}),
2411
2430
  };
2412
2431
  const acceptance = await this.requireRuntime().acceptInputBatch(acceptedBatch);
2432
+ if (isClawclawRuntimeState(acceptedBatch.state) && acceptedBatch.state.stage === 'ended') {
2433
+ this.requireRuntime().closeActionScope(
2434
+ acceptedBatch.scope,
2435
+ acceptedBatch.sourceId === CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId ? 'ACTION_SCOPE_ENDED' : 'GAME_ENDED',
2436
+ );
2437
+ }
2413
2438
  this.sourceCoalescingBoundaryState = nextBoundaryState;
2414
2439
  this.actionSafetyGeneration = actionSafetyGeneration;
2415
2440
  if (acceptedBatch.state.stage === 'ended') {
@@ -173,6 +173,7 @@ export class ActionRegistry {
173
173
  /** Public lifecycle facade used by the unified Behavior Host. */
174
174
  readonly controls = new ControlCoordinator();
175
175
  private readonly abortController = new AbortController();
176
+ private readonly scopeControllers = new Map<string, AbortController>();
176
177
  private readonly inFlight = new Set<Promise<unknown>>();
177
178
  /** Provider-owned settlements no longer hold a control domain, but shutdown still drains them. */
178
179
  private readonly detachedSettlements = new Set<Promise<unknown>>();
@@ -199,6 +200,31 @@ export class ActionRegistry {
199
200
  this.controls.activateScope(scope);
200
201
  }
201
202
 
203
+ private scopeController(scope: ScopeRef): AbortController {
204
+ const key = JSON.stringify([scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId]);
205
+ let controller = this.scopeControllers.get(key);
206
+ if (!controller) {
207
+ controller = new AbortController();
208
+ this.scopeControllers.set(key, controller);
209
+ }
210
+ return controller;
211
+ }
212
+
213
+ /** Fence this scope permanently; a subsequent game/room scope gets its own signal. */
214
+ closeScope(scope: ScopeRef, reason: string): void {
215
+ this.scopeController(scope).abort(new Error(reason));
216
+ }
217
+
218
+ private closedScopeResult<R>(scope: ScopeRef): ActionResult<R> | undefined {
219
+ const signal = this.scopeController(scope).signal;
220
+ if (!signal.aborted) return undefined;
221
+ return {
222
+ scope, actionId: randomUUID(), status: 'failure', source: 'local',
223
+ actionOutcome: 'not_submitted',
224
+ error: { code: signal.reason.message, message: 'This scope has ended; the Action was not submitted.' },
225
+ };
226
+ }
227
+
202
228
  releaseController(controllerId: string, reason = 'released'): void {
203
229
  this.controls.release(controllerId, { reason });
204
230
  }
@@ -215,6 +241,8 @@ export class ActionRegistry {
215
241
  options: ActionAdmissionOptions = {},
216
242
  ): Promise<ActionResult<R>> {
217
243
  if (this.stopping) throw new Error('Action registry is stopping.');
244
+ const closed = this.closedScopeResult<R>(scope);
245
+ if (closed) return closed;
218
246
  const service = this.services.get(capability);
219
247
  if (!service) throw new Error(`Action capability is not available: ${capability}`);
220
248
  const descriptor = service.describeControl?.(action, scope, caller);
@@ -286,6 +314,8 @@ export class ActionRegistry {
286
314
  handoffWaitMs: descriptor?.handoffTimeoutMs,
287
315
  execute: async (controlContext) => {
288
316
  const revalidate = (): ActionExecutionRevalidation => {
317
+ const closed = this.closedScopeResult<never>(scope);
318
+ if (closed) return { status: 'deferred', result: closed };
289
319
  if (options.isAuthorized && !options.isAuthorized()) {
290
320
  this.controls.release(controllerId, { reason: 'worker_authority_revoked' });
291
321
  return {
@@ -310,7 +340,7 @@ export class ActionRegistry {
310
340
  scope,
311
341
  caller,
312
342
  {
313
- signal: this.abortController.signal,
343
+ signal: AbortSignal.any([this.abortController.signal, this.scopeController(scope).signal]),
314
344
  revalidate,
315
345
  latestAcceptedState: options.latestAcceptedState ?? (() => null),
316
346
  },
@@ -254,6 +254,8 @@ export interface RuntimeSourceContext<
254
254
  TEvent = Record<string, unknown>,
255
255
  > extends RuntimeInputSink<TState, TEvent> {
256
256
  currentSegment(): RuntimeSourceSegment;
257
+ /** A Source-confirmed terminal scope revokes Actions without stopping queries or event delivery. */
258
+ closeActionScope(scope: RuntimeScope, reason: string): void;
257
259
  activateSegment(kind: string, identity?: string): Promise<RuntimeScope>;
258
260
  adoptResumeKey(resumeKey: string): RuntimeScope;
259
261
  updateMode(mode: string): RuntimeScope;
@@ -761,7 +761,10 @@ export class RuntimePluginScheduler<
761
761
  this.pumpRequested = true;
762
762
  if (this.pumping || this.stopped) return;
763
763
  this.pumping = true;
764
- queueMicrotask(() => {
764
+ // Yield to transport/Worker message delivery before launching more CPU work.
765
+ // A self-renewing microtask pump can otherwise prevent newly received State
766
+ // from reaching admission, hiding the backlog from bounded catch-up.
767
+ setImmediate(() => {
765
768
  void this.pump().catch((error) => this.failRuntime(error, 'runtime.scheduler')).finally(() => {
766
769
  this.pumping = false;
767
770
  if (this.pumpRequested && !this.stopped && !this.fatalError) this.requestPump();
@@ -672,6 +672,10 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
672
672
  this.sourcePlugins.set(plugin.id, { plugin, handle });
673
673
  }
674
674
 
675
+ closeActionScope(scope: RuntimeScope, reason: string): void {
676
+ this.actions.closeScope(scope, reason);
677
+ }
678
+
675
679
  async activateSegment(kind: string, identity?: string): Promise<RuntimeScope> {
676
680
  this.assertOpen();
677
681
  const previous = this.scope();
@@ -1504,6 +1508,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
1504
1508
  event_watermark: result.eventWatermark,
1505
1509
  current_scope: isCurrentScope,
1506
1510
  total_duration_ms: Math.round(totalMs * 1_000) / 1_000,
1511
+ received_to_ready_ms: Math.max(0, Date.now() - (milliseconds(epoch.receivedAt) ?? Date.now())),
1507
1512
  intake_duration_ms: Math.round((intakeTiming?.intakeTotalMs ?? 0) * 1_000) / 1_000,
1508
1513
  scheduler_duration_ms: Math.round(result.durationMs * 1_000) / 1_000,
1509
1514
  ready_view_finalize_ms: Math.round(finalizeMs * 1_000) / 1_000,
@@ -0,0 +1,34 @@
1
+ import type { GameSyncPerceptionReport } from './game-sync-protocol.js';
2
+ import type { BufferedRawWsLogOptions, RawWsLogStats } from './raw-ws-log.js';
3
+ import type { WsConnectionState } from '../sdk/types.js';
4
+ import type { GameSyncResumeState, WsCloseInfo, WsInputFrame, WsProtocolErrorInfo, WsRecoveryStartedInfo } from './ws-client.js';
5
+
6
+ export interface GameSyncIngressConfig {
7
+ url: string;
8
+ apiKey: string;
9
+ resumeState?: GameSyncResumeState;
10
+ reconnectMaxMs?: number;
11
+ ackIntervalMs?: number;
12
+ maxPendingFrames: number;
13
+ maxPendingBytes: number;
14
+ rawLog?: { path: string; options?: BufferedRawWsLogOptions };
15
+ }
16
+
17
+ export type IngressCommand =
18
+ | { type: 'ack'; token: string; immediate: boolean }
19
+ | { type: 'report'; perceptions: readonly GameSyncPerceptionReport[] }
20
+ | { type: 'telemetry_ack' }
21
+ | { type: 'stop' };
22
+
23
+ export type IngressEvent =
24
+ | { type: 'frame'; frame: WsInputFrame }
25
+ | { type: 'opened'; connectionId: string }
26
+ | { type: 'state'; state: WsConnectionState }
27
+ | { type: 'close'; connectionId: string; info: WsCloseInfo }
28
+ | { type: 'protocol'; info: WsProtocolErrorInfo }
29
+ | { type: 'recovery'; info: WsRecoveryStartedInfo }
30
+ | { type: 'connected' }
31
+ | { type: 'failed'; code: string }
32
+ | { type: 'report_done' }
33
+ | { type: 'telemetry'; attributes: Record<string, unknown> }
34
+ | { type: 'stopped'; rawStats?: RawWsLogStats };
@@ -0,0 +1,153 @@
1
+ import { parentPort, workerData, threadId } from 'node:worker_threads';
2
+ import { readFileSync } from 'node:fs';
3
+ import { monitorEventLoopDelay } from 'node:perf_hooks';
4
+ import { WsConnectionState } from '../sdk/types.js';
5
+ import { WsClient } from './ws-client.js';
6
+ import { BufferedRawWsLog } from './raw-ws-log.js';
7
+ import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js';
8
+
9
+ const port = parentPort!;
10
+ const config = workerData.config as GameSyncIngressConfig;
11
+ const packageVersion = (JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) as { version?: string }).version;
12
+ const raw = config.rawLog ? new BufferedRawWsLog(config.rawLog.path, config.rawLog.options) : undefined;
13
+ const pending = new Map<string, { seq: number; bytes: number; receivedAtMs: number }>();
14
+ let pendingBytes = 0;
15
+ let stopped = false;
16
+ let overloaded = false;
17
+ let restartTimer: ReturnType<typeof setTimeout> | undefined;
18
+ let telemetryPending = false;
19
+ let lastLiveness = 0;
20
+ let lastReceivedSeq = 0;
21
+ let acceptedSeq = config.resumeState?.seq ?? 0;
22
+ let ackSubmittedSeq = 0;
23
+ let receivedFrames = 0;
24
+ let pingCount = 0;
25
+ let pongCount = 0;
26
+ let pongErrors = 0;
27
+ let lastPingAt = 0;
28
+ let lastPongWrittenAt = 0;
29
+ let maxPongWriteMs = 0;
30
+ let maxAckHandoffMs = 0;
31
+ let overloadCount = 0;
32
+ let maxOutstanding = 0;
33
+ const delay = monitorEventLoopDelay({ resolution: 20 });
34
+ delay.enable();
35
+ const post = (message: IngressEvent): void => { if (!stopped || message.type === 'stopped') port.postMessage(message); };
36
+ const client = new WsClient({
37
+ url: config.url, apiKey: config.apiKey, resumeState: config.resumeState,
38
+ reconnectMaxMs: config.reconnectMaxMs, ackIntervalMs: config.ackIntervalMs,
39
+ maxPayloadBytes: config.maxPendingBytes, rawMessageSink: raw,
40
+ handshakeTimeoutMs: 10_000,
41
+ reconnectReady: () => pending.size === 0,
42
+ diagnostic: (name, attributes) => {
43
+ if (name === 'runtime.ws.ping_received') { pingCount++; lastPingAt = Number(attributes.received_at_ms); }
44
+ if (name === 'runtime.ws.pong_written') {
45
+ if (attributes.success) { pongCount++; lastPongWrittenAt = Number(attributes.written_at_ms); }
46
+ else pongErrors++;
47
+ maxPongWriteMs = Math.max(maxPongWriteMs, Number(attributes.duration_ms));
48
+ }
49
+ if (name === 'runtime.ws.ack_submitted') ackSubmittedSeq = Number(attributes.source_seq);
50
+ },
51
+ });
52
+
53
+ function telemetry(force = false): void {
54
+ if (stopped || (telemetryPending && !force)) return;
55
+ telemetryPending = true;
56
+ post({ type: 'telemetry', attributes: {
57
+ sampled_at_ms: Date.now(), connection_id: client.connectionId,
58
+ implementation: 'isolated_gamesync_v1', package_version: packageVersion, node_version: process.version, thread_id: threadId,
59
+ last_liveness_at_ms: lastLiveness, received_frames: receivedFrames,
60
+ received_seq: lastReceivedSeq, source_accepted_seq: acceptedSeq, ack_submitted_seq: ackSubmittedSeq,
61
+ outstanding_frames: pending.size, outstanding_bytes: pendingBytes, max_outstanding_frames: maxOutstanding,
62
+ max_pending_frames: config.maxPendingFrames, max_pending_bytes: config.maxPendingBytes,
63
+ received_ping_count: pingCount, written_pong_count: pongCount, pong_write_errors: pongErrors,
64
+ last_ping_received_at_ms: lastPingAt, last_pong_written_at_ms: lastPongWrittenAt,
65
+ max_pong_write_ms: maxPongWriteMs, max_source_ack_handoff_ms: maxAckHandoffMs,
66
+ overload_count: overloadCount, worker_event_loop_delay_p95_ms: delay.percentile(95) / 1e6,
67
+ worker_event_loop_delay_max_ms: delay.max / 1e6, worker_heap_used_bytes: process.memoryUsage().heapUsed,
68
+ ...(raw ? { raw_log: raw.stats() } : {}),
69
+ } });
70
+ delay.reset();
71
+ }
72
+
73
+ function reconnectWhenDrained(): void {
74
+ if (!overloaded || pending.size || restartTimer || stopped) return;
75
+ restartTimer = setTimeout(() => {
76
+ restartTimer = undefined;
77
+ if (stopped) return;
78
+ overloaded = false;
79
+ void client.connect().catch(() => {});
80
+ }, 1000);
81
+ }
82
+
83
+ client.onStateChange(state => post({ type: 'state', state }));
84
+ client.onConnectionOpened(connectionId => {
85
+ // Socket generation is deliberately separate from monotonically ordered source seq.
86
+ post({ type: 'opened', connectionId });
87
+ });
88
+ client.onLiveness((_connection, atMs) => { lastLiveness = atMs; });
89
+ client.onDisconnect(info => post({ type: 'close', connectionId: client.connectionId, info }));
90
+ const reportedProtocolErrors = new Set<string>();
91
+ client.onProtocolError(info => {
92
+ if (reportedProtocolErrors.has(info.reason)) return;
93
+ reportedProtocolErrors.add(info.reason);
94
+ post({ type: 'protocol', info });
95
+ });
96
+ client.onRecoveryStarted(info => post({ type: 'recovery', info }));
97
+ client.onInputFrame(frame => {
98
+ if (stopped || overloaded) return;
99
+ receivedFrames++;
100
+ lastReceivedSeq = Number(frame.meta.sourceSeq);
101
+ const bytes = Buffer.byteLength(JSON.stringify(frame));
102
+ if (pending.size >= config.maxPendingFrames || pendingBytes + bytes > config.maxPendingBytes) {
103
+ overloadCount++;
104
+ overloaded = true;
105
+ client.disconnect();
106
+ post({ type: 'close', connectionId: client.connectionId, info: {
107
+ code: 1013, reason: 'CCL_INGRESS_BACKLOG_LIMIT', wasClean: false,
108
+ } });
109
+ post({ type: 'state', state: WsConnectionState.Reconnecting });
110
+ telemetry(true);
111
+ reconnectWhenDrained();
112
+ return;
113
+ }
114
+ pending.set(frame.meta.ackToken, { seq: Number(frame.meta.sourceSeq), bytes, receivedAtMs: Date.parse(frame.meta.receivedAt) });
115
+ pendingBytes += bytes;
116
+ maxOutstanding = Math.max(maxOutstanding, pending.size);
117
+ frame.meta.ingress = {
118
+ ...frame.meta.ingress!, workerPostedAtMs: Date.now(), outstandingFrames: pending.size, outstandingBytes: pendingBytes,
119
+ };
120
+ post({ type: 'frame', frame });
121
+ });
122
+
123
+ const timer = setInterval(() => { reportedProtocolErrors.clear(); telemetry(); }, 5000);
124
+ timer.unref();
125
+ port.on('message', (message: IngressCommand) => {
126
+ if (stopped) return;
127
+ if (message.type === 'ack') {
128
+ const entry = pending.get(message.token);
129
+ if (!entry) return;
130
+ client.acknowledge(message.token, message.immediate);
131
+ acceptedSeq = Math.max(acceptedSeq, entry.seq);
132
+ maxAckHandoffMs = Math.max(maxAckHandoffMs, Date.now() - entry.receivedAtMs);
133
+ for (const [token, item] of pending) if (item.seq <= entry.seq) { pending.delete(token); pendingBytes -= item.bytes; }
134
+ reconnectWhenDrained();
135
+ } else if (message.type === 'report') {
136
+ try { client.reportPerceptions(message.perceptions); } finally { post({ type: 'report_done' }); }
137
+ } else if (message.type === 'telemetry_ack') {
138
+ telemetryPending = false;
139
+ } else if (message.type === 'stop') {
140
+ void (async () => {
141
+ client.disconnect();
142
+ telemetry(true);
143
+ stopped = true;
144
+ clearInterval(timer);
145
+ if (restartTimer) clearTimeout(restartTimer);
146
+ delay.disable();
147
+ await raw?.close();
148
+ post({ type: 'stopped', ...(raw ? { rawStats: raw.stats() } : {}) });
149
+ port.close();
150
+ })().catch(() => { post({ type: 'stopped' }); port.close(); });
151
+ }
152
+ });
153
+ void client.connect().then(() => post({ type: 'connected' }), () => post({ type: 'failed', code: 'GAME_SYNC_CONNECT_FAILED' }));
@@ -30,7 +30,6 @@ const MINIMUM_OPERATIONAL_RECORD = /^(?:runtime\.owner\.(?:started|stopped)|runt
30
30
  const FULL_REDUNDANT_DEBUG_RECORDS = new Set([
31
31
  'runtime.input.accepted',
32
32
  'runtime.channel.ready_advanced',
33
- 'runtime.view.ready',
34
33
  'behavior.decide.started',
35
34
  ]);
36
35
 
@@ -38,6 +37,8 @@ const FULL_REDUNDANT_DEBUG_RECORDS = new Set([
38
37
  * Full diagnostics keeps development evidence, not a second copy of the Runtime journals.
39
38
  * Exact per-epoch/plugin outcomes already live in runtime-epochs.sqlite3; the JSONL keeps
40
39
  * exceptional/slow samples and diagnostics that cannot be reconstructed from that journal.
40
+ * runtime.view.ready is retained: intake/finalization and ingress-to-ready latency
41
+ * are not represented by the journal's scheduler-only processing_duration_ms.
41
42
  */
42
43
  function fullObservabilityInputEnabled(input: Readonly<RecordTelemetryInput>): boolean {
43
44
  const severity = input.severity ?? (input.kind === 'error' ? 'error' : 'info');
@@ -0,0 +1,59 @@
1
+ import { monitorEventLoopDelay, performance, PerformanceObserver } from 'node:perf_hooks';
2
+
3
+ /** Full-only process/Owner-loop measurements. Does not retain GC entries or gameplay data. */
4
+ export class RuntimeProcessTimingSampler {
5
+ private readonly delay = monitorEventLoopDelay({ resolution: 20 });
6
+ private readonly observer: PerformanceObserver;
7
+ private previousCpu = process.cpuUsage();
8
+ private previousLoop = performance.eventLoopUtilization();
9
+ private previousAt = performance.now();
10
+ private gcCount = 0;
11
+ private gcMs = 0;
12
+ private stopped = false;
13
+
14
+ constructor() {
15
+ this.observer = new PerformanceObserver((entries) => {
16
+ for (const entry of entries.getEntries()) {
17
+ this.gcCount += 1;
18
+ this.gcMs += entry.duration;
19
+ }
20
+ });
21
+ this.observer.observe({ entryTypes: ['gc'] });
22
+ this.delay.enable();
23
+ }
24
+
25
+ sample(): Readonly<Record<string, number>> {
26
+ const now = performance.now();
27
+ const cpu = process.cpuUsage();
28
+ const loop = performance.eventLoopUtilization();
29
+ const elapsed = now - this.previousAt;
30
+ const deltaLoop = performance.eventLoopUtilization(loop, this.previousLoop);
31
+ const milliseconds = (ns: number): number => Number.isFinite(ns) ? Math.round(ns / 1_000) / 1_000 : 0;
32
+ const result = {
33
+ window_ms: Math.round(elapsed),
34
+ // process.cpuUsage includes Worker threads; this is not Owner-isolate CPU utilization.
35
+ process_cpu_user_ms: (cpu.user - this.previousCpu.user) / 1_000,
36
+ process_cpu_system_ms: (cpu.system - this.previousCpu.system) / 1_000,
37
+ owner_event_loop_utilization: deltaLoop.utilization,
38
+ owner_event_loop_delay_mean_ms: milliseconds(this.delay.mean),
39
+ owner_event_loop_delay_p95_ms: milliseconds(this.delay.percentile(95)),
40
+ owner_event_loop_delay_max_ms: milliseconds(this.delay.max),
41
+ owner_gc_count: this.gcCount,
42
+ owner_gc_duration_ms: Math.round(this.gcMs * 1_000) / 1_000,
43
+ };
44
+ this.previousAt = now;
45
+ this.previousCpu = cpu;
46
+ this.previousLoop = loop;
47
+ this.gcCount = 0;
48
+ this.gcMs = 0;
49
+ this.delay.reset();
50
+ return result;
51
+ }
52
+
53
+ stop(): void {
54
+ if (this.stopped) return;
55
+ this.stopped = true;
56
+ this.observer.disconnect();
57
+ this.delay.disable();
58
+ }
59
+ }
@@ -0,0 +1,196 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ import { EventEmitter } from 'node:events';
3
+ import { WsConnectionState } from '../sdk/types.js';
4
+ import { gameSyncPerceptionReportMessage, type GameSyncPerceptionReport } from './game-sync-protocol.js';
5
+ import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js';
6
+ import type { GameSyncResumeState, WsClient, WsClientConfig, WsInputFrame, WsCloseInfo, WsProtocolErrorInfo, WsRecoveryStartedInfo } from './ws-client.js';
7
+
8
+ export interface ThreadedWsClientConfig extends Omit<WsClientConfig, 'rawMessageSink' | 'reconnectReady'> {
9
+ rawLog?: GameSyncIngressConfig['rawLog'];
10
+ maxPendingFrames?: number;
11
+ maxPendingBytes?: number;
12
+ transportGeneration?: number;
13
+ }
14
+
15
+ /** Source-owned facade. Socket/heartbeat/delta work runs exclusively in the ingress Worker. */
16
+ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
17
+ private readonly events = new EventEmitter();
18
+ private worker?: Worker;
19
+ private stateValue = WsConnectionState.Disconnected;
20
+ private connectionIdValue = '';
21
+ private lastLivenessAt: string | null = null;
22
+ private committed?: GameSyncResumeState;
23
+ private readonly pending = new Map<string, WsInputFrame>();
24
+ private pendingReports = 0;
25
+ private stopped = false;
26
+ private connectedTask?: Promise<void>;
27
+ private resolveConnect?: () => void;
28
+ private rejectConnect?: (error: Error) => void;
29
+ private closeTask: Promise<void> = Promise.resolve();
30
+ private resolveClose?: () => void;
31
+ private closeTimer?: ReturnType<typeof setTimeout>;
32
+ private startupTimer?: ReturnType<typeof setTimeout>;
33
+
34
+ constructor(private readonly config: ThreadedWsClientConfig) {
35
+ const frames = config.maxPendingFrames ?? 10;
36
+ const bytes = config.maxPendingBytes ?? 8 * 1024 * 1024;
37
+ if (!Number.isSafeInteger(frames) || frames < 1 || frames > 1000) throw new Error('GAME_SYNC_FRAME_LIMIT_INVALID');
38
+ if (!Number.isSafeInteger(bytes) || bytes < 1 || bytes > 32 * 1024 * 1024) throw new Error('GAME_SYNC_BYTE_LIMIT_INVALID');
39
+ this.committed = config.resumeState ? structuredClone(config.resumeState) : undefined;
40
+ }
41
+
42
+ get connected(): boolean { return this.stateValue === WsConnectionState.Connected; }
43
+ get state(): WsConnectionState { return this.stateValue; }
44
+ get connectionId(): string { return this.connectionIdValue; }
45
+ get lastPongAt(): string | null { return this.lastLivenessAt; }
46
+ get resumeState(): GameSyncResumeState | undefined { return this.committed ? structuredClone(this.committed) : undefined; }
47
+
48
+ connect(): Promise<void> {
49
+ if (this.connectedTask) return this.connectedTask;
50
+ if (this.stopped) return Promise.reject(new Error('GAME_SYNC_INGRESS_STOPPED'));
51
+ this.stateValue = WsConnectionState.Connecting;
52
+ this.connectedTask = new Promise((resolve, reject) => { this.resolveConnect = resolve; this.rejectConnect = reject; });
53
+ this.closeTask = new Promise(resolve => { this.resolveClose = resolve; });
54
+ this.startupTimer = setTimeout(() => this.fail('GAME_SYNC_INGRESS_START_TIMEOUT'), 20_000);
55
+ this.startupTimer.unref();
56
+ const config: GameSyncIngressConfig = {
57
+ url: this.config.url, apiKey: this.config.apiKey, resumeState: this.committed,
58
+ reconnectMaxMs: this.config.reconnectMaxMs, ackIntervalMs: this.config.ackIntervalMs,
59
+ maxPendingFrames: this.config.maxPendingFrames ?? 10,
60
+ maxPendingBytes: this.config.maxPendingBytes ?? 8 * 1024 * 1024,
61
+ rawLog: this.config.rawLog,
62
+ };
63
+ try {
64
+ this.worker = new Worker(new URL('./framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
65
+ execArgv: [], stdout: true, stderr: true,
66
+ resourceLimits: { maxOldGenerationSizeMb: 128 },
67
+ workerData: { config, runtimeModuleBootstrap: {
68
+ hostUrl: new URL('./game-sync-ingress-worker.ts', import.meta.url).href,
69
+ hooksUrl: new URL('./framework/modules/runtime-module-loader-hooks.mjs', import.meta.url).href,
70
+ sdkAliases: {}, esmModuleRoots: [],
71
+ } },
72
+ });
73
+ this.worker.stdout?.on('data', () => {});
74
+ this.worker.stderr?.on('data', () => {});
75
+ this.worker.on('message', (message: IngressEvent) => this.receive(message));
76
+ this.worker.on('error', () => this.fail('GAME_SYNC_INGRESS_WORKER_FAILED'));
77
+ this.worker.on('exit', (code) => {
78
+ if (!this.stopped) this.fail('GAME_SYNC_INGRESS_WORKER_EXITED');
79
+ if (this.closeTimer) clearTimeout(this.closeTimer);
80
+ this.resolveClose?.();
81
+ this.diagnostic('runtime.ws.ingress_stopped', { exit_code: code });
82
+ });
83
+ } catch {
84
+ this.fail('GAME_SYNC_INGRESS_START_FAILED');
85
+ this.resolveClose?.();
86
+ }
87
+ return this.connectedTask;
88
+ }
89
+
90
+ private receive(message: IngressEvent): void {
91
+ if (message.type === 'telemetry') {
92
+ const a = message.attributes;
93
+ const at = Number(a.last_liveness_at_ms);
94
+ if (at > 0 && !this.stopped) {
95
+ this.lastLivenessAt = new Date(at).toISOString();
96
+ this.events.emit('liveness', String(a.connection_id), at);
97
+ }
98
+ this.diagnostic('runtime.ws.ingress_window', { ...a, owner_observed_at_ms: Date.now() }, Number(a.overload_count) ? 'warn' : 'info');
99
+ this.post({ type: 'telemetry_ack' });
100
+ return;
101
+ }
102
+ if (message.type === 'stopped') {
103
+ if (message.rawStats) this.diagnostic('runtime.raw_ws.capture_stopped', { ...message.rawStats });
104
+ return;
105
+ }
106
+ if (this.stopped) return;
107
+ switch (message.type) {
108
+ case 'connected':
109
+ if (this.startupTimer) clearTimeout(this.startupTimer);
110
+ this.resolveConnect?.(); break;
111
+ case 'failed': this.fail(message.code); break;
112
+ case 'state': this.stateValue = message.state; this.events.emit('state', message.state); break;
113
+ case 'opened': this.connectionIdValue = message.connectionId; this.events.emit('opened', message.connectionId); break;
114
+ case 'close':
115
+ this.connectionIdValue = message.connectionId;
116
+ this.diagnostic('runtime.ws.ingress_disconnected', { code: message.info.code, reason: message.info.reason, pending_frames: this.pending.size }, 'warn');
117
+ this.events.emit('close', message.info); break;
118
+ case 'protocol': this.events.emit('protocol', message.info); break;
119
+ case 'recovery': this.events.emit('recovery', message.info); break;
120
+ case 'report_done': this.pendingReports = Math.max(0, this.pendingReports - 1); break;
121
+ case 'frame': {
122
+ const frame = message.frame;
123
+ frame.meta.ingress = { ...frame.meta.ingress!, ownerReceivedAtMs: Date.now(), transportGeneration: this.config.transportGeneration ?? 1 };
124
+ this.pending.set(frame.meta.ackToken, frame);
125
+ this.lastLivenessAt = frame.meta.receivedAt;
126
+ this.events.emit('liveness', frame.meta.connectionId, Date.parse(frame.meta.receivedAt));
127
+ this.events.emit('frame', frame);
128
+ break;
129
+ }
130
+ }
131
+ }
132
+
133
+ acknowledge(token: string, immediate = false): void {
134
+ const frame = this.pending.get(token);
135
+ if (this.stopped || !frame || frame.meta.connectionId !== this.connectionIdValue) return;
136
+ const seq = Number(frame.meta.sourceSeq);
137
+ if (!this.committed || seq >= this.committed.seq) {
138
+ const { game_id: _gameId, tick: _tick, ...state } = frame.state;
139
+ this.committed = { gameId: frame.meta.gameId, seq, tick: frame.meta.domainTick, locale: frame.meta.locale ?? 'zh-CN', state: structuredClone(state) };
140
+ }
141
+ for (const [key, pending] of this.pending) if (Number(pending.meta.sourceSeq) <= seq) this.pending.delete(key);
142
+ this.post({ type: 'ack', token, immediate });
143
+ }
144
+
145
+ reportPerceptions(perceptions: readonly GameSyncPerceptionReport[]): boolean {
146
+ if (!this.connected || this.stopped || this.pendingReports >= 16) return false;
147
+ const message = gameSyncPerceptionReportMessage(perceptions);
148
+ if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false;
149
+ this.pendingReports++;
150
+ this.post({ type: 'report', perceptions });
151
+ return true;
152
+ }
153
+
154
+ private post(message: IngressCommand): void {
155
+ try { this.worker?.postMessage(message); } catch { if (!this.stopped) this.fail('GAME_SYNC_INGRESS_PORT_FAILED'); }
156
+ }
157
+ private diagnostic(name: string, attributes: Record<string, unknown>, severity: 'debug' | 'info' | 'warn' = 'info'): void {
158
+ try { this.config.diagnostic?.(name, { transport_generation: this.config.transportGeneration ?? 1, ...attributes }, severity); } catch {}
159
+ }
160
+ private fail(code: string): void {
161
+ if (this.stopped) return;
162
+ this.rejectConnect?.(new Error(code));
163
+ this.diagnostic('runtime.ws.ingress_failed', { error_code: code }, 'warn');
164
+ this.stateValue = WsConnectionState.Disconnected;
165
+ this.events.emit('close', { code: 1013, reason: code, wasClean: false } satisfies WsCloseInfo);
166
+ this.disconnect();
167
+ }
168
+
169
+ disconnect(): void {
170
+ if (this.stopped) return;
171
+ this.stopped = true;
172
+ if (this.startupTimer) clearTimeout(this.startupTimer);
173
+ this.stateValue = WsConnectionState.Disconnected;
174
+ this.rejectConnect?.(new Error('GAME_SYNC_INGRESS_STOPPED'));
175
+ this.post({ type: 'stop' });
176
+ this.pending.clear();
177
+ this.events.emit('state', this.stateValue);
178
+ if (this.worker) {
179
+ this.closeTimer = setTimeout(() => {
180
+ this.diagnostic('runtime.ws.ingress_stop_timeout', {}, 'warn');
181
+ void this.worker?.terminate();
182
+ }, 5000);
183
+ this.closeTimer.unref();
184
+ }
185
+ }
186
+ async close(): Promise<void> { this.disconnect(); await this.closeTask; }
187
+ clearHandlers(): void { this.events.removeAllListeners(); }
188
+ private on(event: string, handler: (...args: any[]) => void): () => void { this.events.on(event, handler); return () => { this.events.off(event, handler); }; }
189
+ onInputFrame(handler: (frame: WsInputFrame) => void): () => void { return this.on('frame', handler); }
190
+ onConnectionOpened(handler: (connectionId: string) => void): () => void { return this.on('opened', handler); }
191
+ onLiveness(handler: (connectionId: string, atMs: number) => void): () => void { return this.on('liveness', handler); }
192
+ onProtocolError(handler: (info: WsProtocolErrorInfo) => void): () => void { return this.on('protocol', handler); }
193
+ onRecoveryStarted(handler: (info: WsRecoveryStartedInfo) => void): () => void { return this.on('recovery', handler); }
194
+ onStateChange(handler: (state: WsConnectionState) => void): () => void { return this.on('state', handler); }
195
+ onDisconnect(handler: (info: WsCloseInfo) => void): () => void { return this.on('close', handler); }
196
+ }
@@ -3,6 +3,7 @@
3
3
 
4
4
  import WebSocket from 'ws';
5
5
  import { randomUUID } from 'crypto';
6
+ import { performance } from 'node:perf_hooks';
6
7
  import { WsConnectionState } from '../sdk/types.js';
7
8
  import type { RawWsMessageSink } from './raw-ws-log.js';
8
9
  import {
@@ -31,6 +32,11 @@ export interface WsClientConfig {
31
32
  /** Non-blocking raw server-frame capture owned and closed by the caller. */
32
33
  rawMessageSink?: RawWsMessageSink;
33
34
  resumeState?: GameSyncResumeState;
35
+ maxPayloadBytes?: number;
36
+ handshakeTimeoutMs?: number;
37
+ /** The isolated ingress may wait for already-delivered Source applications before reconnecting. */
38
+ reconnectReady?: () => boolean;
39
+ diagnostic?: (name: string, attributes: Record<string, unknown>, severity?: 'debug' | 'info' | 'warn') => void;
34
40
  }
35
41
 
36
42
  export interface WsCloseInfo {
@@ -72,6 +78,18 @@ export interface WsFrameMeta {
72
78
  ackToken: string;
73
79
  snapshotFallback?: boolean;
74
80
  replayedEventCount?: number;
81
+ /** Local transport clocks, not backend production timestamps. */
82
+ ingress?: {
83
+ socketReceivedAtMs: number;
84
+ decodedAtMs: number;
85
+ decodeDurationMs: number;
86
+ workerPostedAtMs?: number;
87
+ ownerReceivedAtMs?: number;
88
+ outstandingFrames?: number;
89
+ outstandingBytes?: number;
90
+ transportGeneration?: number;
91
+ };
92
+ locale?: 'zh-CN' | 'en-US';
75
93
  }
76
94
 
77
95
  export type WsInputFrame = {
@@ -130,6 +148,8 @@ export class WsClient {
130
148
  private lastAckSent = 0;
131
149
  private readonly seenEventIds = new Set<string>();
132
150
  private readonly rawMessageSink?: RawWsMessageSink;
151
+ private socketReceivedAtMs = 0;
152
+ private decodeStartedAt = 0;
133
153
 
134
154
  private readonly inputFrameHandlers = new Set<(frame: WsInputFrame) => void>();
135
155
  private readonly connectionOpenedHandlers = new Set<(connectionId: string) => void>();
@@ -231,6 +251,9 @@ export class WsClient {
231
251
  this.recoveryEvents = [];
232
252
  const url = gameSyncUrl(this.config.url, this.baseline?.seq);
233
253
  const ws = new WebSocket(url, {
254
+ autoPong: false,
255
+ ...(this.config.handshakeTimeoutMs === undefined ? {} : { handshakeTimeout: this.config.handshakeTimeoutMs }),
256
+ ...(this.config.maxPayloadBytes === undefined ? {} : { maxPayload: this.config.maxPayloadBytes }),
234
257
  headers: {
235
258
  Authorization: `Bearer ${this.config.apiKey}`,
236
259
  'Accept-Language': this.baseline?.locale ?? 'zh-CN',
@@ -251,10 +274,22 @@ export class WsClient {
251
274
 
252
275
  ws.onerror = (error) => reject(error);
253
276
 
254
- (ws as any).on?.('ping', () => this.recordLiveness());
277
+ ws.on('ping', (data) => {
278
+ if (this.ws !== ws) return;
279
+ const receivedAtMs = Date.now();
280
+ this.recordLiveness();
281
+ this.config.diagnostic?.('runtime.ws.ping_received', { received_at_ms: receivedAtMs, bytes: data.length });
282
+ // Reply in the socket-owning isolate, independently of Source/Runtime work.
283
+ ws.pong(data, true, (error) => this.config.diagnostic?.('runtime.ws.pong_written', {
284
+ ping_received_at_ms: receivedAtMs, written_at_ms: Date.now(),
285
+ duration_ms: Math.max(0, Date.now() - receivedAtMs), success: !error,
286
+ }, error ? 'warn' : 'debug'));
287
+ });
255
288
  (ws as any).on?.('pong', () => this.recordLiveness());
256
289
  ws.onmessage = (event) => {
257
290
  if (this.ws !== ws) return;
291
+ this.socketReceivedAtMs = Date.now();
292
+ this.decodeStartedAt = performance.now();
258
293
  const raw = wsMessageToString(event.data);
259
294
  try { this.rawMessageSink?.enqueue(raw); } catch {}
260
295
  this.recordLiveness();
@@ -504,6 +539,12 @@ export class WsClient {
504
539
  meta: {
505
540
  connectionId: this.connectionIdValue,
506
541
  receivedAt: new Date().toISOString(),
542
+ locale: baseline.locale,
543
+ ingress: {
544
+ socketReceivedAtMs: this.socketReceivedAtMs,
545
+ decodedAtMs: Date.now(),
546
+ decodeDurationMs: Math.max(0, performance.now() - this.decodeStartedAt),
547
+ },
507
548
  origin: meta.origin,
508
549
  sourceSeq: baseline.seq,
509
550
  gameId: baseline.gameId,
@@ -540,6 +581,7 @@ export class WsClient {
540
581
  if (this.send({ type: 'game.sync.ack', data: { seq } })) {
541
582
  this.lastAckSent = seq;
542
583
  this.ackDirty = false;
584
+ this.config.diagnostic?.('runtime.ws.ack_submitted', { source_seq: seq, submitted_at_ms: Date.now() });
543
585
  }
544
586
  }
545
587
 
@@ -600,6 +642,11 @@ export class WsClient {
600
642
  this.reconnectAttempt += 1;
601
643
  this.reconnectTimer = setTimeout(() => {
602
644
  if (!this.shouldReconnect) return;
645
+ if (this.config.reconnectReady?.() === false) {
646
+ this.reconnectAttempt = Math.max(0, this.reconnectAttempt - 1);
647
+ this.scheduleReconnect();
648
+ return;
649
+ }
603
650
  this.setState(WsConnectionState.Connecting);
604
651
  void this.openSocket().catch(() => {});
605
652
  }, delay);