@series-inc/rundot-syncplay 6.0.0-rc.112 → 6.0.0-rc.113

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.
@@ -36,7 +36,7 @@ export const physicsProfileWasmMetadata = Object.freeze({
36
36
  "sourceHash": "4ca971eb52456e0141b37c4700f877b15b776df4be327000ff7a42d0aef106e6",
37
37
  "wasmSha256": "4eb4d6848a74b25b5d21c377be92ad1a0d78f1f96f12934ddae683c99a7c0afc",
38
38
  "artifact": "profile",
39
- "packageVersion": "6.0.0-rc.112",
39
+ "packageVersion": "6.0.0-rc.113",
40
40
  "compilerFlags": [
41
41
  "-std=c++20",
42
42
  "-O3",
@@ -36,7 +36,7 @@ export const physicsWasmMetadata = Object.freeze({
36
36
  "sourceHash": "76bbbac134fa1abfc823dc6d324b663da3bcdb80bc09c28fc025736d2d9cc03f",
37
37
  "wasmSha256": "19d53336de18d53eed555cd80f25cdb5e9e43c6491c06e93f672be7683737ac7",
38
38
  "artifact": "production",
39
- "packageVersion": "6.0.0-rc.112",
39
+ "packageVersion": "6.0.0-rc.113",
40
40
  "compilerFlags": [
41
41
  "-std=c++20",
42
42
  "-O3",
@@ -50,7 +50,7 @@ export const physics2dWasmMetadata = Object.freeze({
50
50
  "sourceHash": "b4ae2139eb68bf6c797af143c07cec8b80e732662f9f9cda219bf76de63e0934",
51
51
  "wasmSha256": "633aeb98cb199b120cc7b5a855a620e01ab73d5cd8b6427cb7949eafecfdf1f0",
52
52
  "artifact": "production",
53
- "packageVersion": "6.0.0-rc.112",
53
+ "packageVersion": "6.0.0-rc.113",
54
54
  "compilerFlags": [
55
55
  "-std=c++20",
56
56
  "-O3",
@@ -14,7 +14,7 @@ export interface SnapshotDonationDiagnostic {
14
14
  readonly outputBytes: number;
15
15
  }
16
16
  export interface SyncplayDiagnostic {
17
- readonly code: 'api.deprecated' | 'snapshot.donor';
17
+ readonly code: 'api.deprecated' | 'snapshot.donor' | 'snapshot.joiner';
18
18
  readonly key: string;
19
19
  readonly message: string;
20
20
  readonly replacement: string;
@@ -84,9 +84,9 @@ export interface DeterministicAuthorityRoomConfig {
84
84
  /** Abandon a donor transfer that has not completed after this many ticks. Default 600. */
85
85
  readonly transferTimeoutTicks?: number;
86
86
  /**
87
- * Snapshot transfer ceiling in bytes for this room's collector (default
88
- * DEFAULT_MAX_SNAPSHOT_BYTES). Offers above it are rejected with
89
- * `snapshot-too-large`; keep it equal to the clients' configured ceiling.
87
+ * Snapshot wire limit for this room (default 4 MiB).
88
+ * The room rejects offers above the limit with `snapshot-too-large`.
89
+ * A client accepts up to 6,000,000 bytes.
90
90
  */
91
91
  readonly maxSnapshotBytes?: number;
92
92
  /**
@@ -3,7 +3,8 @@ import { assertKinetixRuntimeIdentity, kinetixRuntimeIdentitiesEqual as equalRun
3
3
  import { invariant } from './errors.js';
4
4
  import { createInputAuthority } from './input-authority.js';
5
5
  import { createBinaryDeterministicLocalAuthoritySnapshotChunkEnvelope, createBinaryDeterministicLocalAuthoritySnapshotCompleteEnvelope, createBinaryDeterministicLocalAuthoritySnapshotOfferEnvelope, createBinaryDeterministicLocalAuthoritySnapshotRefusalEnvelope, createBinaryDeterministicLocalAuthoritySnapshotRequestEnvelope, createDeterministicLocalAuthoritySnapshotChunkEnvelope, createDeterministicLocalAuthoritySnapshotCompleteEnvelope, createDeterministicLocalAuthoritySnapshotOfferEnvelope, createDeterministicLocalAuthoritySnapshotRefusalEnvelope, createDeterministicLocalAuthoritySnapshotRequestEnvelope, decodeBinaryDeterministicLocalAuthorityWireEnvelope, decodeDeterministicLocalAuthorityWireEnvelope, } from './local-authority-wire.js';
6
- import { DEFAULT_BINARY_SNAPSHOT_CHUNK_SIZE, snapshotHydratedByteLimit, DEFAULT_MAX_SNAPSHOT_BYTES, DEFAULT_SNAPSHOT_CHUNK_SIZE, TEXT_COMPRESSED_SNAPSHOT_PREFIX, createBinarySnapshotTransferFromBytes, createSnapshotTransferCollector, createSnapshotTransferFromBytes, decodeDeterministicStateSnapshotInternal, encodeDeterministicStateSnapshot, encodeTextWrappedBinarySnapshot, deterministicRoomDescriptorHash, restampBinarySnapshotWitnesses, } from './session-snapshot.js';
6
+ import { DEFAULT_BINARY_SNAPSHOT_CHUNK_SIZE, snapshotHydratedByteLimit, DEFAULT_SNAPSHOT_CHUNK_SIZE, TEXT_COMPRESSED_SNAPSHOT_PREFIX, createBinarySnapshotTransferFromBytes, createSnapshotTransferCollector, createSnapshotTransferFromBytes, decodeDeterministicStateSnapshotInternal, encodeDeterministicStateSnapshot, encodeTextWrappedBinarySnapshot, deterministicRoomDescriptorHash, restampBinarySnapshotWitnesses, } from './session-snapshot.js';
7
+ import { DEFAULT_MAX_SNAPSHOT_BYTES, MAX_SNAPSHOT_WIRE_BYTES, isPositiveSnapshotByteLimit } from './snapshot-limits.js';
7
8
  import { MAX_KINETIX_SESSION_CONFIG_BYTES, MAX_SYNCPLAY_COMMAND_PAYLOAD_BYTES, MAX_SYNCPLAY_EPHEMERAL_PAYLOAD_BYTES, decodeDeterministicSessionMessage, encodeDeterministicSessionMessage, } from './session-wire.js';
8
9
  import { createSyncplaySecretAuthority, } from './secret-authority.js';
9
10
  import { DEFAULT_SEAT_POLICY, validateSeatPolicy, createInitialSeatControlState, allocatable, findAvailableSeat, applyTransition, expireSeatHolds, createSeatCheckpoint, restoreSeatControlState, } from './seat-control.js';
@@ -138,15 +139,11 @@ export function createDeterministicAuthorityRoom(transport, config) {
138
139
  }
139
140
  const sessionMsgType = config.sessionMsgType ?? DEFAULT_SESSION_MSG_TYPE;
140
141
  const binarySessionMsgType = config.binarySessionMsgType ?? `${sessionMsgType}-bin`;
141
- /**
142
- * The largest snapshot the room stores. A snapshot request carries it only when it is not the default. The
143
- * default equals the client's default, so a room at the default limit sends no field and its messages stay as
144
- * before. A host that builds the room from the snapshot policy always sets the limit, often to the default.
145
- */
146
142
  const storedSnapshotLimitBytes = config.maxSnapshotBytes ?? DEFAULT_MAX_SNAPSHOT_BYTES;
147
- const requestSnapshotLimitBytes = storedSnapshotLimitBytes === DEFAULT_MAX_SNAPSHOT_BYTES
143
+ // Low-level rooms and stored bundles can use a limit above the client maximum.
144
+ const advertisedSnapshotLimitBytes = storedSnapshotLimitBytes === DEFAULT_MAX_SNAPSHOT_BYTES
148
145
  ? undefined
149
- : storedSnapshotLimitBytes;
146
+ : Math.min(storedSnapshotLimitBytes, MAX_SNAPSHOT_WIRE_BYTES);
150
147
  const historyRetentionTicks = requireTickCount('historyRetentionTicks', config.historyRetentionTicks ?? DEFAULT_HISTORY_RETENTION_TICKS);
151
148
  // The ring keeps at least four redundancy windows, see createSessionAuthority.
152
149
  const historyRingTicks = Math.max(historyRetentionTicks, config.redundancyWindowTicks * 4);
@@ -163,13 +160,13 @@ export function createDeterministicAuthorityRoom(transport, config) {
163
160
  let seed = config.seed;
164
161
  let generation = config.restoreFrom?.generation ?? 0;
165
162
  invariant(Number.isInteger(generation) && generation >= 0, 'restored generation must be a non-negative integer', 'authority-room.restore-generation');
166
- if (config.maxSnapshotBytes !== undefined && (!Number.isInteger(config.maxSnapshotBytes) || config.maxSnapshotBytes < 1)) {
163
+ if (config.maxSnapshotBytes !== undefined && !isPositiveSnapshotByteLimit(config.maxSnapshotBytes)) {
167
164
  throw new Error(`createDeterministicAuthorityRoom: maxSnapshotBytes must be a positive integer, received ${config.maxSnapshotBytes}`);
168
165
  }
169
166
  // With no explicit hydrated limit, the room must accept at least what its own wire limit allows.
170
167
  // The client uses the same floor, so the two sides agree.
171
168
  const snapshotDecodeLimits = config.maxHydratedSnapshotBytes === undefined
172
- ? { defaultHydratedByteFloor: config.maxSnapshotBytes ?? 0 }
169
+ ? { defaultHydratedByteFloor: storedSnapshotLimitBytes }
173
170
  : { maxHydratedBytes: config.maxHydratedSnapshotBytes };
174
171
  const maxHydratedSnapshotBytes = snapshotHydratedByteLimit(undefined, snapshotDecodeLimits);
175
172
  if (!Number.isInteger(maxHydratedSnapshotBytes) || maxHydratedSnapshotBytes < 1) {
@@ -795,7 +792,7 @@ export function createDeterministicAuthorityRoom(transport, config) {
795
792
  transferId,
796
793
  chunkSize: DEFAULT_BINARY_SNAPSHOT_CHUNK_SIZE,
797
794
  });
798
- transport.sendBinaryTo(playerId, binarySessionMsgType, createBinaryDeterministicLocalAuthoritySnapshotOfferEnvelope(nextWireSequence(), binaryTransfer));
795
+ transport.sendBinaryTo(playerId, binarySessionMsgType, createBinaryDeterministicLocalAuthoritySnapshotOfferEnvelope(nextWireSequence(), binaryTransfer, advertisedSnapshotLimitBytes));
799
796
  for (let index = 0; index < binaryTransfer.chunks.length; index += 1) {
800
797
  transport.sendBinaryTo(playerId, binarySessionMsgType, createBinaryDeterministicLocalAuthoritySnapshotChunkEnvelope(nextWireSequence(), binaryTransfer, index));
801
798
  }
@@ -808,7 +805,7 @@ export function createDeterministicAuthorityRoom(transport, config) {
808
805
  transferId,
809
806
  chunkSize: DEFAULT_SNAPSHOT_CHUNK_SIZE,
810
807
  });
811
- transport.sendTo(playerId, sessionMsgType, createDeterministicLocalAuthoritySnapshotOfferEnvelope(nextWireSequence(), transfer));
808
+ transport.sendTo(playerId, sessionMsgType, createDeterministicLocalAuthoritySnapshotOfferEnvelope(nextWireSequence(), transfer, advertisedSnapshotLimitBytes));
812
809
  for (let index = 0; index < transfer.chunks.length; index += 1) {
813
810
  transport.sendTo(playerId, sessionMsgType, createDeterministicLocalAuthoritySnapshotChunkEnvelope(nextWireSequence(), transfer, index));
814
811
  }
@@ -2084,7 +2081,7 @@ export function createDeterministicAuthorityRoom(transport, config) {
2084
2081
  minFrame: tick + 1,
2085
2082
  startedAt: now,
2086
2083
  timeoutTicks: transferTimeoutTicks,
2087
- collector: createSnapshotTransferCollector(config.maxSnapshotBytes === undefined ? {} : { maxSnapshotBytes: config.maxSnapshotBytes }),
2084
+ collector: createSnapshotTransferCollector({ maxSnapshotBytes: storedSnapshotLimitBytes }),
2088
2085
  isRetry,
2089
2086
  targetTick: tick,
2090
2087
  generation,
@@ -2094,10 +2091,10 @@ export function createDeterministicAuthorityRoom(transport, config) {
2094
2091
  const requestIdentity = { descriptorHash: roomDescriptorHash, configHash: transferRequestId };
2095
2092
  const transferBudgetMs = pendingTransfer.timeoutTicks * 1000 / config.tickRateHz;
2096
2093
  if (transport.sendBinaryTo !== undefined && binaryCapablePlayers.has(donorId)) {
2097
- transport.sendBinaryTo(donorId, binarySessionMsgType, createBinaryDeterministicLocalAuthoritySnapshotRequestEnvelope(nextWireSequence(), requestIdentity, tick + 1, transferBudgetMs, requestSnapshotLimitBytes));
2094
+ transport.sendBinaryTo(donorId, binarySessionMsgType, createBinaryDeterministicLocalAuthoritySnapshotRequestEnvelope(nextWireSequence(), requestIdentity, tick + 1, transferBudgetMs, advertisedSnapshotLimitBytes));
2098
2095
  return;
2099
2096
  }
2100
- transport.sendTo(donorId, sessionMsgType, createDeterministicLocalAuthoritySnapshotRequestEnvelope(nextWireSequence(), requestIdentity, tick + 1, transferBudgetMs, requestSnapshotLimitBytes));
2097
+ transport.sendTo(donorId, sessionMsgType, createDeterministicLocalAuthoritySnapshotRequestEnvelope(nextWireSequence(), requestIdentity, tick + 1, transferBudgetMs, advertisedSnapshotLimitBytes));
2101
2098
  }
2102
2099
  /**
2103
2100
  * The newest fully reported tick above the stored snapshot that has a donor
@@ -59,8 +59,8 @@ export declare function createBinaryDeterministicLocalAuthoritySnapshotRequestEn
59
59
  */
60
60
  export declare function createDeterministicLocalAuthoritySnapshotRefusalEnvelope(sequence: number, identity: DeterministicLocalAuthoritySnapshotIdentity, reason: string, maxSnapshotBytes: number): string;
61
61
  export declare function createBinaryDeterministicLocalAuthoritySnapshotRefusalEnvelope(sequence: number, identity: DeterministicLocalAuthoritySnapshotIdentity, reason: string, maxSnapshotBytes: number): Uint8Array;
62
- export declare function createDeterministicLocalAuthoritySnapshotOfferEnvelope(sequence: number, transfer: DeterministicLocalAuthoritySnapshotTransfer): string;
63
- export declare function createBinaryDeterministicLocalAuthoritySnapshotOfferEnvelope(sequence: number, transfer: DeterministicLocalAuthorityBinarySnapshotTransfer): Uint8Array;
62
+ export declare function createDeterministicLocalAuthoritySnapshotOfferEnvelope(sequence: number, transfer: DeterministicLocalAuthoritySnapshotTransfer, maxSnapshotBytes?: number): string;
63
+ export declare function createBinaryDeterministicLocalAuthoritySnapshotOfferEnvelope(sequence: number, transfer: DeterministicLocalAuthorityBinarySnapshotTransfer, maxSnapshotBytes?: number): Uint8Array;
64
64
  export declare function createDeterministicLocalAuthoritySnapshotChunkEnvelope(sequence: number, transfer: DeterministicLocalAuthoritySnapshotTransfer, chunkIndex: number): string;
65
65
  export declare function createBinaryDeterministicLocalAuthoritySnapshotChunkEnvelope(sequence: number, transfer: DeterministicLocalAuthorityBinarySnapshotTransfer, chunkIndex: number): Uint8Array;
66
66
  export declare function createDeterministicLocalAuthoritySnapshotCompleteEnvelope(sequence: number, transferId: string): string;
@@ -1,4 +1,5 @@
1
1
  import { canonicalStringify, cloneCanonical, defaultChecksum, decodeUtf8, encodeUtf8 } from './canonical.js';
2
+ import { MAX_SNAPSHOT_WIRE_BYTES, isSnapshotWireByteLimit } from './snapshot-limits.js';
2
3
  export const deterministicLocalAuthorityWireProtocol = 'rdm-local-authority/v2';
3
4
  export const deterministicLocalAuthorityBinaryWireMagic = 'SYNWIR02';
4
5
  const MAX_ENVELOPE_BYTES = 2 * 1024 * 1024;
@@ -239,6 +240,12 @@ export function decodeBinaryDeterministicLocalAuthorityWireEnvelope(encoded) {
239
240
  checksum: expectedDigest.toString(16).padStart(8, '0'),
240
241
  };
241
242
  }
243
+ /** A limit a room puts on the wire: absent, or an integer the receiver accepts. */
244
+ function assertWireByteLimit(message, maxSnapshotBytes) {
245
+ if (maxSnapshotBytes !== undefined && !isSnapshotWireByteLimit(maxSnapshotBytes)) {
246
+ throw new Error(`Syncplay snapshot ${message} maxSnapshotBytes must be an integer from 1 to ${MAX_SNAPSHOT_WIRE_BYTES}`);
247
+ }
248
+ }
242
249
  /**
243
250
  * `maxSnapshotBytes` (since 6.0.0-rc.112) is the room's stored snapshot
244
251
  * limit. A donor without a Worker uses it to choose a payload that fits.
@@ -246,9 +253,7 @@ export function decodeBinaryDeterministicLocalAuthorityWireEnvelope(encoded) {
246
253
  function snapshotRequestPayload(identity, minFrame, transferBudgetMs, maxSnapshotBytes) {
247
254
  assertIdentity(identity);
248
255
  assertFrame(minFrame);
249
- if (maxSnapshotBytes !== undefined && (!Number.isSafeInteger(maxSnapshotBytes) || maxSnapshotBytes < 1)) {
250
- throw new Error('Syncplay snapshot request maxSnapshotBytes must be a positive integer');
251
- }
256
+ assertWireByteLimit('request', maxSnapshotBytes);
252
257
  return {
253
258
  identity, minFrame,
254
259
  ...(transferBudgetMs === undefined ? {} : { transferBudgetMs }),
@@ -286,8 +291,9 @@ export function createBinaryDeterministicLocalAuthoritySnapshotRefusalEnvelope(s
286
291
  kind: 'snapshot-refusal', sequence, payload: { identity, reason, maxSnapshotBytes },
287
292
  });
288
293
  }
289
- export function createDeterministicLocalAuthoritySnapshotOfferEnvelope(sequence, transfer) {
294
+ export function createDeterministicLocalAuthoritySnapshotOfferEnvelope(sequence, transfer, maxSnapshotBytes) {
290
295
  assertTransfer(transfer);
296
+ assertWireByteLimit('offer', maxSnapshotBytes);
291
297
  return encodeDeterministicLocalAuthorityWireEnvelope({
292
298
  kind: 'snapshot-offer',
293
299
  sequence,
@@ -299,12 +305,14 @@ export function createDeterministicLocalAuthoritySnapshotOfferEnvelope(sequence,
299
305
  chunkCount: transfer.chunks.length,
300
306
  totalBytes: transfer.snapshotBytes.length,
301
307
  chunkChecksums: transfer.chunkChecksums,
308
+ ...(maxSnapshotBytes === undefined ? {} : { maxSnapshotBytes }),
302
309
  ...(transfer.compressed === true ? { compressed: true } : {}),
303
310
  },
304
311
  });
305
312
  }
306
- export function createBinaryDeterministicLocalAuthoritySnapshotOfferEnvelope(sequence, transfer) {
313
+ export function createBinaryDeterministicLocalAuthoritySnapshotOfferEnvelope(sequence, transfer, maxSnapshotBytes) {
307
314
  assertBinaryTransfer(transfer);
315
+ assertWireByteLimit('offer', maxSnapshotBytes);
308
316
  return encodeBinaryDeterministicLocalAuthorityWireEnvelope({
309
317
  kind: 'snapshot-offer',
310
318
  sequence,
@@ -316,6 +324,7 @@ export function createBinaryDeterministicLocalAuthoritySnapshotOfferEnvelope(seq
316
324
  chunkCount: transfer.chunks.length,
317
325
  totalBytes: transfer.binarySnapshotBytes.byteLength,
318
326
  chunkChecksums: transfer.chunkChecksums,
327
+ ...(maxSnapshotBytes === undefined ? {} : { maxSnapshotBytes }),
319
328
  binary: true,
320
329
  },
321
330
  });
@@ -122,11 +122,7 @@ export interface NetworkedSyncplayClientOptions<State, Input, Checkpoint = unkno
122
122
  * pulse/edge command codecs so a one-shot can never be replayed speculatively.
123
123
  */
124
124
  readonly remoteInputPrediction?: SyncplayRemoteInputPrediction;
125
- /**
126
- * Snapshot transfer ceiling in bytes for the client collector (default
127
- * DEFAULT_MAX_SNAPSHOT_BYTES). Must match the room's configured ceiling — a
128
- * client ceiling below the room's snapshot size silently breaks late-join.
129
- */
125
+ /** Optional cap on received snapshots and staged donor fallback. The room advertises its own limit. */
130
126
  readonly maxSnapshotBytes?: number;
131
127
  /**
132
128
  * Decoded/hydrated raw snapshot payload ceiling in bytes (default
@@ -8,7 +8,8 @@ import { digestSnapshotBytes } from './snapshot-upload.js';
8
8
  import { parseSyncplayChecksumPolicy, SYNCPLAY_DEFAULT_CHECKSUM_CADENCE_TICKS } from './checksum-policy.js';
9
9
  import { createApiDiagnostics, emitSyncplayDiagnostic } from './api-diagnostics.js';
10
10
  import { createBinaryDeterministicLocalAuthoritySnapshotChunkEnvelope, createBinaryDeterministicLocalAuthoritySnapshotCompleteEnvelope, createBinaryDeterministicLocalAuthoritySnapshotOfferEnvelope, createDeterministicLocalAuthoritySnapshotChunkEnvelope, createDeterministicLocalAuthoritySnapshotCompleteEnvelope, createDeterministicLocalAuthoritySnapshotOfferEnvelope, decodeBinaryDeterministicLocalAuthorityWireEnvelope, encodeBinaryDeterministicLocalAuthorityWireEnvelope, encodeDeterministicLocalAuthorityWireEnvelope, decodeDeterministicLocalAuthorityWireEnvelope, } from './local-authority-wire.js';
11
- import { DEFAULT_BINARY_SNAPSHOT_CHUNK_SIZE, DEFAULT_MAX_SNAPSHOT_BYTES, DEFAULT_SNAPSHOT_CHUNK_SIZE, TEXT_COMPRESSED_SNAPSHOT_PREFIX, snapshotHydratedByteLimit, createBinarySnapshotTransferFromBytes, createSnapshotTransferCollector, createSnapshotTransferFromBytes, decodeDeterministicStateSnapshotInternal, deterministicRoomDescriptorHash, encodeBinaryDeterministicStateSnapshot, encodeTextWrappedBinarySnapshot, } from './session-snapshot.js';
11
+ import { DEFAULT_BINARY_SNAPSHOT_CHUNK_SIZE, DEFAULT_SNAPSHOT_CHUNK_SIZE, TEXT_COMPRESSED_SNAPSHOT_PREFIX, snapshotHydratedByteLimit, createBinarySnapshotTransferFromBytes, createSnapshotTransferCollector, createSnapshotTransferFromBytes, decodeDeterministicStateSnapshotInternal, deterministicRoomDescriptorHash, encodeBinaryDeterministicStateSnapshot, encodeTextWrappedBinarySnapshot, } from './session-snapshot.js';
12
+ import { DEFAULT_MAX_SNAPSHOT_BYTES, MAX_SNAPSHOT_WIRE_BYTES, isPositiveSnapshotByteLimit, isSnapshotWireByteLimit, } from './snapshot-limits.js';
12
13
  import { DEFAULT_BASELINE_PAGE_BYTES, decodeSnapshotBaselineDelta, encodeSnapshotBaselineDelta, isBaselineDeltaSnapshotBytes, } from './snapshot-baseline-delta.js';
13
14
  import { attachSnapshotWorkDigest, installedPhysicsRuntimes3D, physicsTransferBaselines3D, legacyVoxelPageDiffRuntimes3D, } from './physics/installed-checkpoint3d.js';
14
15
  import { MAX_SYNCPLAY_COMMAND_PAYLOAD_BYTES, decodeDeterministicSessionMessage, encodeDeterministicSessionMessage, } from './session-wire.js';
@@ -441,8 +442,8 @@ export function createNetworkedSyncplayClient(options) {
441
442
  let rollbackUsedThisTurn = false;
442
443
  const sessionMsgType = options.sessionMsgType ?? DEFAULT_MSG_TYPE;
443
444
  const maxPredictionTicks = options.maxPredictionTicks ?? DEFAULT_MAX_PREDICTION;
444
- if (options.maxSnapshotBytes !== undefined && (!Number.isInteger(options.maxSnapshotBytes) || options.maxSnapshotBytes < 1)) {
445
- throw new Error(`createNetworkedSyncplayClient: maxSnapshotBytes must be a positive integer, received ${options.maxSnapshotBytes}`);
445
+ if (options.maxSnapshotBytes !== undefined && !isSnapshotWireByteLimit(options.maxSnapshotBytes)) {
446
+ throw new Error(`createNetworkedSyncplayClient: maxSnapshotBytes must be an integer from 1 to ${MAX_SNAPSHOT_WIRE_BYTES}, received ${options.maxSnapshotBytes}`);
446
447
  }
447
448
  const snapshotDecodeLimits = options.maxHydratedSnapshotBytes === undefined
448
449
  ? { defaultHydratedByteFloor: options.maxSnapshotBytes ?? 0 }
@@ -469,9 +470,7 @@ export function createNetworkedSyncplayClient(options) {
469
470
  if (options.serializeStateAsync !== undefined && typeof options.serializeStateAsync !== 'function') {
470
471
  throw new TypeError('createNetworkedSyncplayClient: serializeStateAsync must be a function');
471
472
  }
472
- const snapshotCollectorOptions = options.maxSnapshotBytes === undefined
473
- ? {}
474
- : { maxSnapshotBytes: options.maxSnapshotBytes };
473
+ const localSnapshotLimitBytes = options.maxSnapshotBytes ?? MAX_SNAPSHOT_WIRE_BYTES;
475
474
  const checksumCadenceTicks = options.checksumCadenceTicks ?? DEFAULT_CHECKSUM_CADENCE_TICKS;
476
475
  const pingIntervalMs = options.pacing?.pingIntervalMs ?? DEFAULT_PING_INTERVAL_MS;
477
476
  const targetLeadTicks = options.pacing?.targetLeadTicks ?? DEFAULT_TARGET_LEAD_TICKS;
@@ -633,7 +632,7 @@ export function createNetworkedSyncplayClient(options) {
633
632
  const reportedTicks = [];
634
633
  const pendingConfirmedChecksums = new Map();
635
634
  let lastAutoReportedTick = -1;
636
- let transferCollector = createSnapshotTransferCollector(snapshotCollectorOptions);
635
+ let transferCollector = createSnapshotTransferCollector();
637
636
  let snapshotWitnesses;
638
637
  /** Created at session-start from the room tick rate; undefined before it or when the room has no valid rate. */
639
638
  let donorUpload;
@@ -1133,16 +1132,16 @@ export function createNetworkedSyncplayClient(options) {
1133
1132
  tickZeroBaselinePromise = undefined;
1134
1133
  releaseTickZeroBaselinePin();
1135
1134
  }
1136
- function deactivateGeneration(caught) {
1135
+ function deactivateGeneration(caught, sessionFailure) {
1137
1136
  runtimeEpoch += 1;
1138
1137
  cancelDonorSnapshot();
1139
1138
  releaseDonorBaselines();
1140
1139
  pendingConfirmedChecksums.clear();
1141
1140
  const failure = caught instanceof Error ? caught : new Error(String(caught), { cause: caught });
1142
- secretFailure = session === undefined ? failure
1141
+ secretFailure = sessionFailure ?? (session === undefined ? failure
1143
1142
  : new SyncplayError(`SYNCPLAY_RUNTIME_GENERATION_FAILED: ${failure.message}`, {
1144
1143
  code: 'client.generation-failed', cause: caught,
1145
- });
1144
+ }));
1146
1145
  failPendingHydrationWaiters(secretFailure);
1147
1146
  return secretFailure;
1148
1147
  }
@@ -1316,21 +1315,22 @@ export function createNetworkedSyncplayClient(options) {
1316
1315
  // A throw here would escape into the transport's socket handler, so the
1317
1316
  // refusal reaches the game through whenReady(), pump() and the
1318
1317
  // transport's reportSessionError.
1319
- const failure = sessionRefusalError(message);
1320
- swapAbort?.abort();
1321
- swapAbort = undefined;
1322
- swapGeneration = undefined;
1323
- swapBuffer.length = 0;
1324
- renewReadiness();
1325
- deactivateGeneration(failure);
1326
- secretFailure = failure;
1327
- readyReject?.(failure);
1328
- readyResolve = undefined;
1329
- readyReject = undefined;
1330
- // Last, so a throw from the game's own handler cannot skip a step above.
1331
- options.transport.reportSessionError?.(failure);
1318
+ failSession(sessionRefusalError(message));
1332
1319
  }
1333
1320
  }
1321
+ function failSession(failure, reportOriginalToHydration = false) {
1322
+ swapAbort?.abort();
1323
+ swapAbort = undefined;
1324
+ swapGeneration = undefined;
1325
+ swapBuffer.length = 0;
1326
+ renewReadiness();
1327
+ deactivateGeneration(failure, reportOriginalToHydration ? failure : undefined);
1328
+ secretFailure = failure;
1329
+ readyReject?.(failure);
1330
+ readyResolve = undefined;
1331
+ readyReject = undefined;
1332
+ options.transport.reportSessionError?.(failure);
1333
+ }
1334
1334
  function beginSessionSwap(message, nextGeneration) {
1335
1335
  cancelDonorSnapshot();
1336
1336
  renewReadiness();
@@ -1594,7 +1594,7 @@ export function createNetworkedSyncplayClient(options) {
1594
1594
  pendingConfirmedChecksums.clear();
1595
1595
  lastAutoReportedTick = -1;
1596
1596
  ownInputSubstitutions = 0;
1597
- transferCollector = createSnapshotTransferCollector(snapshotCollectorOptions);
1597
+ transferCollector = createSnapshotTransferCollector();
1598
1598
  snapshotWitnesses = undefined;
1599
1599
  donorUpload?.dispose();
1600
1600
  donorUpload = message.tickRateHz > 0
@@ -2503,7 +2503,18 @@ export function createNetworkedSyncplayClient(options) {
2503
2503
  return;
2504
2504
  }
2505
2505
  if (envelope.kind === 'snapshot-offer') {
2506
- transferCollector.offer(envelope.payload);
2506
+ const { maxSnapshotBytes = DEFAULT_MAX_SNAPSHOT_BYTES } = envelope.payload;
2507
+ if (!isSnapshotWireByteLimit(maxSnapshotBytes)) {
2508
+ const message = `The room sent a snapshot offer limit outside the range 1 to ${MAX_SNAPSHOT_WIRE_BYTES} bytes.`;
2509
+ const failure = new SyncplayError(message, { code: 'client.snapshot-offer-limit-invalid' });
2510
+ hydrationFailedError = failure;
2511
+ emitSyncplayDiagnostic(options.diagnostics, {
2512
+ code: 'snapshot.joiner', key: 'snapshot.offer-limit-invalid', message, replacement: '', migration: '',
2513
+ });
2514
+ failSession(failure, true);
2515
+ return;
2516
+ }
2517
+ transferCollector.offer(envelope.payload, Math.min(maxSnapshotBytes, localSnapshotLimitBytes));
2507
2518
  return;
2508
2519
  }
2509
2520
  if (envelope.kind === 'snapshot-chunk') {
@@ -2663,11 +2674,16 @@ export function createNetworkedSyncplayClient(options) {
2663
2674
  const sendBinary = binaryRequest ? options.transport.sendBinary : undefined;
2664
2675
  const transferBudgetMs = typeof payload.transferBudgetMs === 'number' && Number.isFinite(payload.transferBudgetMs)
2665
2676
  && payload.transferBudgetMs > 0 ? payload.transferBudgetMs : 10_000;
2666
- // A room sends the limit it stores snapshots under when that limit is not the default. So a request without the
2667
- // field means the default limit, and a donor with a larger limit of its own still fits the room.
2668
- const roomSnapshotLimit = typeof payload.maxSnapshotBytes === 'number' && Number.isSafeInteger(payload.maxSnapshotBytes)
2669
- && payload.maxSnapshotBytes > 0 ? payload.maxSnapshotBytes : DEFAULT_MAX_SNAPSHOT_BYTES;
2670
- const snapshotLimitBytes = Math.min(roomSnapshotLimit, options.maxSnapshotBytes ?? DEFAULT_MAX_SNAPSHOT_BYTES);
2677
+ const requestLimit = payload.maxSnapshotBytes;
2678
+ let roomSnapshotLimit = DEFAULT_MAX_SNAPSHOT_BYTES;
2679
+ if (isPositiveSnapshotByteLimit(requestLimit)) {
2680
+ roomSnapshotLimit = Math.min(requestLimit, MAX_SNAPSHOT_WIRE_BYTES);
2681
+ }
2682
+ else if (requestLimit !== undefined) {
2683
+ donorDiagnostic('snapshot.request-limit-invalid', 'The snapshot request has an invalid room limit. The donor uses 4 MiB.');
2684
+ }
2685
+ const snapshotLimitBytes = Math.min(roomSnapshotLimit, localSnapshotLimitBytes);
2686
+ const requestExceedsHardLimit = isPositiveSnapshotByteLimit(requestLimit) && requestLimit > MAX_SNAPSHOT_WIRE_BYTES;
2671
2687
  if (lastDonorRequest !== undefined && lastDonorRequest.id === requestConfigHash
2672
2688
  && lastDonorRequest.frame === minFrame && lastDonorRequest.budgetMs === transferBudgetMs
2673
2689
  && lastDonorRequest.binary === binaryRequest && (donorEncodeAbort !== undefined || donorUpload?.hasPending)) {
@@ -2938,6 +2954,12 @@ export function createNetworkedSyncplayClient(options) {
2938
2954
  sequence: donorTransferCounter * 1000,
2939
2955
  };
2940
2956
  const outputBytes = encoded.bytes.byteLength;
2957
+ if (requestExceedsHardLimit && outputBytes > snapshotLimitBytes) {
2958
+ if (!abortController.signal.aborted) {
2959
+ emitDonorRefusal(minTick, minFrame, capturedSlot, offerIdentity, binaryRequest, sendBinary, 'SYNCPLAY_DONOR_SNAPSHOT_LIMIT_EXCEEDED');
2960
+ }
2961
+ return;
2962
+ }
2941
2963
  const prepared = await measurePhase('prepare upload', () => prepareDonorUpload(encoded.bytes, sendBinary !== undefined, uploadIdentity, donorSnapshotBudgetMs, abortController.signal, fallbackPacing, encoded.usedWorker));
2942
2964
  if (capturedRuntimeEpoch === runtimeEpoch
2943
2965
  && baseline !== undefined && encoded.computedBaselineChecksum !== undefined) {
@@ -3041,7 +3063,12 @@ export function createNetworkedSyncplayClient(options) {
3041
3063
  const binarySnapshot = encodeBinaryDeterministicStateSnapshot(active.schemaIdentity.stateDigestDomain === 'syncplay.state-report/2'
3042
3064
  ? { ...commonFields, v: 3, runtimePayloadChecksum: measureSnapshotPhase('digestMs', () => sha256Hex(payloadBytes)), witnesses: 1 }
3043
3065
  : { ...commonFields, v: 2 });
3044
- emitDonorSnapshotTransfer(binarySnapshot, tick, slot, offerIdentity, upload, sendBinary);
3066
+ if (requestExceedsHardLimit && binarySnapshot.byteLength > snapshotLimitBytes) {
3067
+ emitDonorRefusal(minTick, minFrame, slot, offerIdentity, binaryRequest, sendBinary, 'SYNCPLAY_DONOR_SNAPSHOT_LIMIT_EXCEEDED');
3068
+ }
3069
+ else {
3070
+ emitDonorSnapshotTransfer(binarySnapshot, tick, slot, offerIdentity, upload, sendBinary);
3071
+ }
3045
3072
  return { deltaMode, rawBytes, outputBytes: binarySnapshot.byteLength };
3046
3073
  }));
3047
3074
  reportDonation('synchronous', donation.deltaMode, donation.rawBytes, donation.outputBytes);
@@ -3570,7 +3597,7 @@ export function createNetworkedSyncplayClient(options) {
3570
3597
  }
3571
3598
  if (hydrationWaiters.length === 0) {
3572
3599
  try {
3573
- transferCollector = createSnapshotTransferCollector(snapshotCollectorOptions);
3600
+ transferCollector = createSnapshotTransferCollector();
3574
3601
  }
3575
3602
  catch { }
3576
3603
  }
@@ -2,6 +2,7 @@ import { type KinetixPinnedSnapshot, type KinetixRuntimeIdentity } from '@series
2
2
  import type { EncodedInput } from './input-authority.js';
3
3
  import type { DeterministicLocalAuthorityBinarySnapshotTransfer, DeterministicLocalAuthoritySnapshotIdentity, DeterministicLocalAuthoritySnapshotTransfer } from './local-authority-wire.js';
4
4
  import type { SyncplaySeatState } from './types.js';
5
+ export { DEFAULT_MAX_SNAPSHOT_BYTES } from './snapshot-limits.js';
5
6
  /**
6
7
  * Session-state snapshot payload + transfer plumbing for snapshot late-join (§6 M5.5).
7
8
  *
@@ -157,8 +158,6 @@ export declare const SNAPSHOT_CHUNK_ENVELOPE_OVERHEAD_BYTES = 512;
157
158
  export declare const MAX_JSON_ESCAPE_EXPANSION = 4;
158
159
  export declare const DEFAULT_SNAPSHOT_CHUNK_SIZE = 262144;
159
160
  export declare const DEFAULT_BINARY_SNAPSHOT_CHUNK_SIZE = 262144;
160
- /** Wire transfer budget (4 MiB compressed wire bytes). */
161
- export declare const DEFAULT_MAX_SNAPSHOT_BYTES = 4194304;
162
161
  /** Hydrated raw runtime payload budget (32 MiB decompressed/reconstructed bytes). */
163
162
  export declare const DEFAULT_MAX_HYDRATED_SNAPSHOT_BYTES = 33554432;
164
163
  export declare function snapshotHydratedByteLimit(mode: SnapshotDeltaMode | undefined, options: DecodeDeterministicStateSnapshotOptions): number;
@@ -197,7 +196,7 @@ export type SnapshotTransferCompleteResult = {
197
196
  };
198
197
  export type SnapshotTransferRejection = 'malformed-snapshot-offer' | 'snapshot-too-large' | 'unknown-snapshot-transfer' | 'snapshot-chunk-index-out-of-range' | 'duplicate-snapshot-chunk' | 'snapshot-chunk-checksum-mismatch' | 'malformed-snapshot-chunk' | 'malformed-snapshot-complete' | 'missing-snapshot-chunk' | 'snapshot-byte-length-mismatch' | 'snapshot-transfer-checksum-mismatch';
199
198
  export interface SnapshotTransferCollector {
200
- offer(payload: Readonly<Record<string, unknown>>): SnapshotTransferStepResult;
199
+ offer(payload: Readonly<Record<string, unknown>>, maxSnapshotBytes?: number): SnapshotTransferStepResult;
201
200
  chunk(payload: Readonly<Record<string, unknown>>): SnapshotTransferStepResult;
202
201
  complete(payload: Readonly<Record<string, unknown>>): SnapshotTransferCompleteResult;
203
202
  abort(transferId: string): void;
@@ -3,6 +3,8 @@ import { SyncplayError } from './errors.js';
3
3
  import { assertKinetixRuntimeIdentity, kinetixPinnedSnapshotSymbol, sha256Hex, } from '@series-inc/rundot-syncplay/core/runtime';
4
4
  import { compressSnapshotBytes, decompressSnapshotBytes, decompressLzmaSnapshot, isCompressedSnapshotBytes, } from './snapshot-compression.js';
5
5
  import { isBaselineDeltaSnapshotBytes, SNAPSHOT_BASELINE_DELTA_HEADER_BYTES, } from './snapshot-baseline-delta.js';
6
+ import { DEFAULT_MAX_SNAPSHOT_BYTES, isPositiveSnapshotByteLimit, isSnapshotWireByteLimit } from './snapshot-limits.js';
7
+ export { DEFAULT_MAX_SNAPSHOT_BYTES } from './snapshot-limits.js';
6
8
  export const BINARY_SNAPSHOT_MAGIC = 'SYNSNP04';
7
9
  export const TEXT_COMPRESSED_SNAPSHOT_PREFIX = 'synsnp04:';
8
10
  const BINARY_SNAPSHOT_HEADER_BYTES = 20;
@@ -712,8 +714,6 @@ export const SNAPSHOT_CHUNK_ENVELOPE_OVERHEAD_BYTES = 512;
712
714
  export const MAX_JSON_ESCAPE_EXPANSION = 4;
713
715
  export const DEFAULT_SNAPSHOT_CHUNK_SIZE = 262_144;
714
716
  export const DEFAULT_BINARY_SNAPSHOT_CHUNK_SIZE = 262_144;
715
- /** Wire transfer budget (4 MiB compressed wire bytes). */
716
- export const DEFAULT_MAX_SNAPSHOT_BYTES = 4_194_304;
717
717
  /** Hydrated raw runtime payload budget (32 MiB decompressed/reconstructed bytes). */
718
718
  export const DEFAULT_MAX_HYDRATED_SNAPSHOT_BYTES = 33_554_432;
719
719
  export function snapshotHydratedByteLimit(mode, options) {
@@ -774,11 +774,15 @@ function maxTextWrappedSnapshotOfferBytes(maxSnapshotBytes) {
774
774
  return TEXT_COMPRESSED_SNAPSHOT_PREFIX.length + Math.ceil(maxSnapshotBytes / 3) * 4;
775
775
  }
776
776
  export function createSnapshotTransferCollector(options = {}) {
777
- const maxSnapshotBytes = options.maxSnapshotBytes ?? DEFAULT_MAX_SNAPSHOT_BYTES;
778
- const maxCompressedTextBytes = maxTextWrappedSnapshotOfferBytes(maxSnapshotBytes);
777
+ const defaultMaxSnapshotBytes = options.maxSnapshotBytes ?? DEFAULT_MAX_SNAPSHOT_BYTES;
779
778
  const pending = new Map();
780
779
  return {
781
- offer(payload) {
780
+ offer(payload, maxSnapshotBytes) {
781
+ // The room can set a trusted collector budget for an older stored bundle.
782
+ const limit = maxSnapshotBytes ?? defaultMaxSnapshotBytes;
783
+ if (maxSnapshotBytes === undefined ? !isPositiveSnapshotByteLimit(limit) : !isSnapshotWireByteLimit(maxSnapshotBytes)) {
784
+ return { accepted: false, reason: 'malformed-snapshot-offer' };
785
+ }
782
786
  const identity = parseIdentity(payload.identity);
783
787
  const binaryFlag = payload.binary;
784
788
  const compressedFlag = payload.compressed;
@@ -803,7 +807,7 @@ export function createSnapshotTransferCollector(options = {}) {
803
807
  if (isCompressedText && payload.totalBytes <= TEXT_COMPRESSED_SNAPSHOT_PREFIX.length) {
804
808
  return { accepted: false, reason: 'malformed-snapshot-offer' };
805
809
  }
806
- const maxAllowedOfferBytes = isCompressedText ? maxCompressedTextBytes : maxSnapshotBytes;
810
+ const maxAllowedOfferBytes = isCompressedText ? maxTextWrappedSnapshotOfferBytes(limit) : limit;
807
811
  if (payload.totalBytes > maxAllowedOfferBytes) {
808
812
  return { accepted: false, reason: 'snapshot-too-large' };
809
813
  }
@@ -814,6 +818,7 @@ export function createSnapshotTransferCollector(options = {}) {
814
818
  snapshotChecksum: payload.snapshotChecksum,
815
819
  chunkCount: payload.chunkCount,
816
820
  totalBytes: payload.totalBytes,
821
+ maxSnapshotBytes: limit,
817
822
  chunkChecksums: [...payload.chunkChecksums],
818
823
  binary: binaryFlag === true,
819
824
  compressed: isCompressedText,
@@ -936,7 +941,7 @@ export function createSnapshotTransferCollector(options = {}) {
936
941
  }
937
942
  const padding = encodedPart.endsWith('==') ? 2 : encodedPart.endsWith('=') ? 1 : 0;
938
943
  const decodedBytes = (encodedPart.length / 4) * 3 - padding;
939
- if (decodedBytes > maxSnapshotBytes) {
944
+ if (decodedBytes > transfer.maxSnapshotBytes) {
940
945
  return { accepted: false, reason: 'snapshot-too-large' };
941
946
  }
942
947
  }
@@ -1,5 +1,6 @@
1
1
  import { SyncplayError } from './errors.js';
2
2
  import { SYNCPLAY_DEFAULT_CHECKSUM_CADENCE_TICKS } from './checksum-policy.js';
3
+ import { DEFAULT_MAX_SNAPSHOT_BYTES, MAX_SNAPSHOT_WIRE_BYTES } from './snapshot-limits.js';
3
4
  /**
4
5
  * The one parser for a deterministic room's snapshot options.
5
6
  *
@@ -38,7 +39,7 @@ export const SYNCPLAY_REMOVED_SNAPSHOT_ROOM_CONFIG_KEYS = {
38
39
  /** Ranges for the creator block. Seconds unless the name says bytes. */
39
40
  const SYNCPLAY_SNAPSHOT_CONFIG_LIMITS = {
40
41
  backgroundSeconds: { min: 10, max: 3600, default: 60 },
41
- maxBytes: { min: 65_536, max: 4_194_304, default: 4_194_304 },
42
+ maxBytes: { min: 65_536, max: MAX_SNAPSHOT_WIRE_BYTES },
42
43
  transferTimeoutSeconds: { min: 1, max: 60, default: 10 },
43
44
  historyRetentionSeconds: { min: 60, max: 14_400 },
44
45
  // The wait runs before the room admits the player. The room server answers
@@ -85,7 +86,6 @@ export function syncplayFreshJoinMaxAgeTicks(tickRateHz) {
85
86
  }
86
87
  /** The history ring default in ticks. It does not scale with the tick rate, so existing rooms keep it. */
87
88
  const SYNCPLAY_DEFAULT_HISTORY_RETENTION_TICKS = 216_000;
88
- const DEFAULT_MAX_SNAPSHOT_BYTES = SYNCPLAY_SNAPSHOT_CONFIG_LIMITS.maxBytes.default;
89
89
  /**
90
90
  * Parse and validate the snapshot options of one deterministic room. Throws a
91
91
  * SyncplayError with code `syncplay.snapshot-config-invalid` on any invalid
@@ -0,0 +1,6 @@
1
+ /** Wire transfer budget (4 MiB compressed wire bytes). */
2
+ export declare const DEFAULT_MAX_SNAPSHOT_BYTES = 4194304;
3
+ /** Leaves room for record metadata under the worker's 8 MiB JSON limit after Base64. */
4
+ export declare const MAX_SNAPSHOT_WIRE_BYTES = 6000000;
5
+ export declare function isPositiveSnapshotByteLimit(value: unknown): value is number;
6
+ export declare function isSnapshotWireByteLimit(value: unknown): value is number;
@@ -0,0 +1,10 @@
1
+ /** Wire transfer budget (4 MiB compressed wire bytes). */
2
+ export const DEFAULT_MAX_SNAPSHOT_BYTES = 4_194_304;
3
+ /** Leaves room for record metadata under the worker's 8 MiB JSON limit after Base64. */
4
+ export const MAX_SNAPSHOT_WIRE_BYTES = 6_000_000;
5
+ export function isPositiveSnapshotByteLimit(value) {
6
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
7
+ }
8
+ export function isSnapshotWireByteLimit(value) {
9
+ return isPositiveSnapshotByteLimit(value) && value <= MAX_SNAPSHOT_WIRE_BYTES;
10
+ }
@@ -34,7 +34,7 @@ export interface EncodeSessionSnapshotOffThreadOptions extends EncodeBinaryDeter
34
34
  readonly preferWorker?: boolean;
35
35
  /** Transfer ownership of `runtimePayloadBytes.buffer` into the Worker when standalone (default `false`). */
36
36
  readonly transferInput?: boolean;
37
- /** Keep the input until a Worker has completed its first job. */
37
+ /** Transfer the input only after the Worker reports ready. */
38
38
  readonly transferInputAfterWorkerStart?: boolean;
39
39
  /** Optional cancellation signal for queued/in-flight off-thread snapshot encoding. */
40
40
  readonly signal?: AbortSignal;
@@ -591,7 +591,7 @@ function armStartupTimer(bridge) {
591
591
  const timer = setTimeout(check, STARTUP_TIMER_STEP_MS);
592
592
  bridge.startupTimer = timer;
593
593
  // An idle startup timer must not keep a Node process alive. holdBridge refs it while a job waits for the Worker.
594
- if (pendingJobs.size === 0)
594
+ if (startupWaiters.size === 0)
595
595
  timer.unref?.();
596
596
  };
597
597
  schedule();
@@ -633,12 +633,40 @@ let nextJobId = 1;
633
633
  let nextBaselineCacheId = 1;
634
634
  const baselineIds = new WeakMap();
635
635
  const pendingJobs = new Map();
636
+ const startupWaiters = new Set();
637
+ function waitForWorkerReady(bridge, signal) {
638
+ return new Promise((resolve, reject) => {
639
+ signal?.throwIfAborted();
640
+ if (activeBridge !== bridge) {
641
+ throw bridge.startupFailure ?? new SnapshotWorkerFailure('Worker closed during startup');
642
+ }
643
+ function remove() {
644
+ startupWaiters.delete(waiter);
645
+ signal?.removeEventListener('abort', abort);
646
+ if (activeBridge === bridge && startupWaiters.size === 0 && pendingJobs.size === 0)
647
+ holdBridge(bridge, false);
648
+ }
649
+ function abort() {
650
+ remove();
651
+ reject(signal?.reason);
652
+ }
653
+ const waiter = {
654
+ ready() { remove(); resolve(); },
655
+ fail(error) { remove(); reject(error); },
656
+ };
657
+ signal?.addEventListener('abort', abort, { once: true });
658
+ startupWaiters.add(waiter);
659
+ holdBridge(bridge, true);
660
+ });
661
+ }
636
662
  function handleWorkerMessage(bridge, raw) {
637
663
  if (activeBridge !== bridge)
638
664
  return;
639
665
  if (typeof raw === 'object' && raw !== null && raw.kind === 'ready') {
640
666
  bridge.ready = true;
641
667
  clearStartupTimer(bridge);
668
+ for (const waiter of startupWaiters)
669
+ waiter.ready();
642
670
  return;
643
671
  }
644
672
  const reply = raw;
@@ -647,7 +675,6 @@ function handleWorkerMessage(bridge, raw) {
647
675
  const pending = pendingJobs.get(reply.id);
648
676
  if (pending === undefined)
649
677
  return;
650
- bridge.ready = true;
651
678
  pendingJobs.delete(reply.id);
652
679
  pending.cleanupAbort?.();
653
680
  if (pendingJobs.size === 0)
@@ -658,6 +685,8 @@ function handleWorkerMessage(bridge, raw) {
658
685
  pending.reject(new Error(reply.error ?? 'Worker snapshot encode failed'));
659
686
  }
660
687
  function failAllPendingWorkerJobs(error) {
688
+ for (const waiter of startupWaiters)
689
+ waiter.fail(error);
661
690
  const entries = [...pendingJobs.values()];
662
691
  pendingJobs.clear();
663
692
  for (const entry of entries) {
@@ -776,6 +805,9 @@ export async function terminateSnapshotEncodeWorker() {
776
805
  function postSnapshotWorkerJob(bridge, message, transfer, signal) {
777
806
  return new Promise((resolve, reject) => {
778
807
  signal?.throwIfAborted();
808
+ if (activeBridge !== bridge || !bridge.ready) {
809
+ throw bridge.startupFailure ?? new SnapshotWorkerFailure('Worker closed before the job started');
810
+ }
779
811
  const id = nextJobId++;
780
812
  function removeJob() {
781
813
  if (!pendingJobs.delete(id))
@@ -790,10 +822,7 @@ function postSnapshotWorkerJob(bridge, message, transfer, signal) {
790
822
  return;
791
823
  reject(signal.reason);
792
824
  if (activeBridge === bridge) {
793
- // Before ready, the Worker runs no job yet, so the abort cancels only this job. The bridge's startup timer
794
- // decides whether the Worker starts. A ready Worker may still run the job, so replace it.
795
- if (!bridge.ready)
796
- return;
825
+ // The Worker can still run a posted job. Replace the Worker to stop it.
797
826
  activeBridge = undefined;
798
827
  failAllPendingWorkerJobs(new SnapshotWorkerFailure('Worker cancelled'));
799
828
  void bridge.terminate();
@@ -854,6 +883,8 @@ export async function prepareDonorUpload(bytes, binary, identity, budgetMs, sign
854
883
  if (preferWorker && bridge === null)
855
884
  throw new SnapshotWorkerFailure('Worker closed before upload');
856
885
  if (bridge !== null) {
886
+ if (!bridge.ready)
887
+ await waitForWorkerReady(bridge, signal);
857
888
  const owned = bytes.buffer instanceof ArrayBuffer
858
889
  && bytes.byteOffset === 0 && bytes.length === bytes.buffer.byteLength;
859
890
  const reply = await postSnapshotWorkerJob(bridge, {
@@ -954,6 +985,10 @@ export async function encodeDonorSnapshotOffThread(snapshot, options = {}) {
954
985
  options.onWorkerSelected?.();
955
986
  let transfersInput = false;
956
987
  try {
988
+ // Keep the payload on the host until the Worker can take ownership.
989
+ if (!bridge.ready)
990
+ await waitForWorkerReady(bridge, options.signal);
991
+ options.signal?.throwIfAborted();
957
992
  let baselineCacheId = 0;
958
993
  let sendBaselineBytes;
959
994
  if (options.baselineBytes !== undefined && snapshot.deltaMode === undefined) {
@@ -968,6 +1003,7 @@ export async function encodeDonorSnapshotOffThread(snapshot, options = {}) {
968
1003
  if (activeBridge !== bridge) {
969
1004
  throw bridge.startupFailure ?? new SnapshotWorkerFailure('Worker closed during baseline preparation');
970
1005
  }
1006
+ options.signal?.throwIfAborted();
971
1007
  }
972
1008
  }
973
1009
  transfersInput =
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@series-inc/rundot-syncplay",
3
- "version": "6.0.0-rc.112",
3
+ "version": "6.0.0-rc.113",
4
4
  "description": "Kinetix orchestration, rollback, replay, late-join, and deterministic networking for RUN.game",
5
5
  "repository": {
6
6
  "type": "git",