@valerypopoff/rivet2-core 2.32.0 → 2.34.0

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.
@@ -428,6 +428,22 @@ export class HttpCallNodeImpl extends NodeImpl {
428
428
  }
429
429
  async process(inputs, context) {
430
430
  const requestAttempts = this.data.retryOnNon200 ? createHttpCallRequestAttempts() : undefined;
431
+ let ownedResponse;
432
+ const discardResponse = () => {
433
+ const response = ownedResponse;
434
+ ownedResponse = undefined;
435
+ try {
436
+ const body = response?.body;
437
+ if (body && !body.locked) {
438
+ // Custom streams can reject or never finish cancellation. Releasing
439
+ // an unused reply must not delay a run or replace its original error.
440
+ void body.cancel().catch(() => undefined);
441
+ }
442
+ }
443
+ catch {
444
+ // A custom Fetch body can also throw synchronously during cleanup.
445
+ }
446
+ };
431
447
  try {
432
448
  const method = getInputOrData(this.data, inputs, 'method', 'string');
433
449
  const url = getInputOrData(this.data, inputs, 'url', 'string');
@@ -472,13 +488,15 @@ export class HttpCallNodeImpl extends NodeImpl {
472
488
  }
473
489
  const performRequest = async () => {
474
490
  try {
475
- return await fetch(url, {
491
+ const response = await fetch(url, {
476
492
  method,
477
493
  headers,
478
494
  body,
479
495
  signal: context.signal,
480
496
  mode: 'cors',
481
497
  });
498
+ ownedResponse = response;
499
+ return response;
482
500
  }
483
501
  catch (err) {
484
502
  if (isAbortError(err, context.signal)) {
@@ -510,6 +528,7 @@ export class HttpCallNodeImpl extends NodeImpl {
510
528
  const repeatTimes = normalizeHttpRetryCount(this.data.retryOnNon200RepeatTimes);
511
529
  const cooldownMs = normalizeHttpRetryCooldownMs(this.data.retryOnNon200CooldownMs);
512
530
  for (let attempt = 0; response.status !== 200 && attempt < repeatTimes; attempt++) {
531
+ discardResponse();
513
532
  await waitForRetryCooldown(cooldownMs, context.signal);
514
533
  response = await performTrackedRequest();
515
534
  }
@@ -537,6 +556,7 @@ export class HttpCallNodeImpl extends NodeImpl {
537
556
  const output = responseMetadataOutputs;
538
557
  if (this.data.isBinaryOutput) {
539
558
  const responseBlob = await response.blob();
559
+ ownedResponse = undefined;
540
560
  output['binary'] = {
541
561
  type: 'binary',
542
562
  value: new Uint8Array(await responseBlob.arrayBuffer()),
@@ -544,6 +564,7 @@ export class HttpCallNodeImpl extends NodeImpl {
544
564
  }
545
565
  else {
546
566
  const responseText = await response.text();
567
+ ownedResponse = undefined;
547
568
  output['res_body'] = {
548
569
  type: 'string',
549
570
  value: responseText,
@@ -589,6 +610,9 @@ export class HttpCallNodeImpl extends NodeImpl {
589
610
  }
590
611
  throw error;
591
612
  }
613
+ finally {
614
+ discardResponse();
615
+ }
592
616
  }
593
617
  }
594
618
  export const httpCallNode = nodeDefinition(HttpCallNodeImpl, 'Http Call');
@@ -31,14 +31,14 @@ const toRecordedEventMap = {
31
31
  processId,
32
32
  ...(resultOrigin === undefined ? {} : { resultOrigin }),
33
33
  }, execution),
34
- nodeFinish: ({ node, outputs, processId, resultOrigin, durationMs, splitRunDurationMs, streamingWatchTerminal, execution }) => withExecution(withDuration({
34
+ nodeFinish: ({ node, outputs, processId, resultOrigin, durationMs, splitRunDurationMs, streamingWatchTerminal, execution, }) => withExecution(withDuration({
35
35
  nodeId: node.id,
36
36
  outputs,
37
37
  processId,
38
38
  ...(resultOrigin === undefined ? {} : { resultOrigin }),
39
39
  ...(streamingWatchTerminal ? { streamingWatchTerminal: true } : {}),
40
40
  }, durationMs, splitRunDurationMs), execution),
41
- nodeError: ({ node, error, processId, outputs, splitOutputs, resultOrigin, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
41
+ nodeError: ({ node, error, processId, outputs, splitOutputs, resultOrigin, durationMs, splitRunDurationMs, execution, }) => withExecution(withDuration({
42
42
  nodeId: node.id,
43
43
  error: typeof error === 'string' ? error : error.stack,
44
44
  processId,
@@ -173,16 +173,20 @@ function mapValuesDeep(obj, fn) {
173
173
  });
174
174
  }
175
175
  if (isPlainObject(obj)) {
176
- return Object.fromEntries(Object.entries(obj).map(([key, value]) => {
177
- if (isPlainObject(value) || Array.isArray(value)) {
178
- return [key, mapValuesDeep(value, fn)];
179
- }
180
- return [key, fn(value)];
181
- }));
176
+ // Read the properties before recursing, preserving accessor order. Reuse
177
+ // these copied entries instead of allocating a second array of key/value
178
+ // pairs. fromEntries also keeps __proto__ an ordinary own property.
179
+ const entries = Object.entries(obj);
180
+ for (const entry of entries) {
181
+ const value = entry[1];
182
+ entry[1] = isPlainObject(value) || Array.isArray(value) ? mapValuesDeep(value, fn) : fn(value);
183
+ }
184
+ return Object.fromEntries(entries);
182
185
  }
183
186
  return fn(obj);
184
187
  }
185
188
  function serializeToObject(recording) {
189
+ const stringHashes = new Map();
186
190
  const serialized = {
187
191
  version: 1,
188
192
  recording,
@@ -203,9 +207,13 @@ function serializeToObject(recording) {
203
207
  return `$ASSET:${id}`;
204
208
  }
205
209
  }
206
- if (typeof val === 'string' && !val.startsWith('$ASSET:') && val.length > 30) {
207
- const hash = fnv1a(val, { size: 32 });
208
- serialized.strings[`${hash}`] = val;
210
+ if (typeof val === 'string' && val.length > 30 && !val.startsWith('$ASSET:')) {
211
+ let hash = stringHashes.get(val);
212
+ if (hash === undefined) {
213
+ hash = String(fnv1a(val, { size: 32 }));
214
+ stringHashes.set(val, hash);
215
+ }
216
+ serialized.strings[hash] = val;
209
217
  return `$STRING:${hash}`;
210
218
  }
211
219
  return val;
@@ -243,26 +251,67 @@ export class ExecutionRecorder {
243
251
  #emitter;
244
252
  #includePartialOutputs;
245
253
  #includeTrace;
254
+ #capturePolicy;
255
+ #captureDiscarded = false;
246
256
  constructor(options = {}) {
247
257
  this.#emitter = new Emittery();
248
258
  this.#emitter.bindMethods(this, ['on', 'off', 'once']);
249
259
  this.#includePartialOutputs = options.includePartialOutputs ?? false;
250
260
  this.#includeTrace = options.includeTrace ?? false;
261
+ try {
262
+ this.#capturePolicy = options.createCapturePolicy?.(this);
263
+ }
264
+ catch {
265
+ this.#captureDiscarded = true;
266
+ }
267
+ }
268
+ get captureDiscarded() {
269
+ return this.#captureDiscarded;
270
+ }
271
+ /** Release replay data, without cancelling the graph or its terminal listener. */
272
+ discard() {
273
+ this.#captureDiscarded = true;
274
+ this.#events.length = 0;
275
+ const policy = this.#capturePolicy;
276
+ this.#capturePolicy = undefined;
277
+ try {
278
+ policy?.release();
279
+ }
280
+ catch {
281
+ /* Recording accounting cannot fail a graph. */
282
+ }
283
+ }
284
+ #append(event) {
285
+ if (this.#captureDiscarded)
286
+ return;
287
+ try {
288
+ if (this.#capturePolicy && !this.#capturePolicy.retain(event)) {
289
+ this.discard();
290
+ return;
291
+ }
292
+ }
293
+ catch {
294
+ this.discard();
295
+ return;
296
+ }
297
+ this.#events.push(event);
251
298
  }
252
299
  on = undefined;
253
300
  off = undefined;
254
301
  once = undefined;
255
302
  recordSocket(channel, options = {}) {
256
- return new Promise((resolve) => {
257
- this.recordingId = nanoid();
303
+ return new Promise((resolve, reject) => {
258
304
  let settled = false;
305
+ const detach = () => {
306
+ channel.removeEventListener('message', listener);
307
+ channel.removeEventListener('close', onClose);
308
+ options.signal?.removeEventListener('abort', onOwnerDisposed);
309
+ };
259
310
  const finish = (emitFinishedRecording) => {
260
311
  if (settled)
261
312
  return;
262
313
  settled = true;
263
- channel.removeEventListener('message', listener);
264
- channel.removeEventListener('close', onClose);
265
- options.signal?.removeEventListener('abort', onOwnerDisposed);
314
+ detach();
266
315
  if (emitFinishedRecording) {
267
316
  emitDetached(this.#emitter, 'finish', {
268
317
  recording: this.getRecording(),
@@ -298,64 +347,94 @@ export class ExecutionRecorder {
298
347
  if (getEventProjectScope(data) !== undefined) {
299
348
  return;
300
349
  }
301
- this.#events.push(toRecordedEvent(message, data));
350
+ if (!this.#captureDiscarded)
351
+ this.#append(toRecordedEvent(message, data));
302
352
  if (isSocketRecordingTerminalEvent(message)) {
303
353
  finish(true);
304
354
  }
305
355
  };
306
- if (options.signal?.aborted) {
307
- onOwnerDisposed();
308
- return;
356
+ try {
357
+ this.recordingId = nanoid();
358
+ if (options.signal?.aborted) {
359
+ onOwnerDisposed();
360
+ return;
361
+ }
362
+ channel.addEventListener('message', listener);
363
+ channel.addEventListener('close', onClose, { once: true });
364
+ options.signal?.addEventListener('abort', onOwnerDisposed, { once: true });
365
+ if (channel.readyState === CLOSED_WEBSOCKET_READY_STATE)
366
+ onClose();
309
367
  }
310
- channel.addEventListener('message', listener);
311
- channel.addEventListener('close', onClose, { once: true });
312
- options.signal?.addEventListener('abort', onOwnerDisposed, { once: true });
313
- if (channel.readyState === CLOSED_WEBSOCKET_READY_STATE) {
314
- onClose();
368
+ catch (error) {
369
+ settled = true;
370
+ try {
371
+ detach();
372
+ }
373
+ catch {
374
+ /* Keep the original setup failure and release capture ownership. */
375
+ }
376
+ this.discard();
377
+ reject(error);
315
378
  }
316
379
  });
317
380
  }
318
381
  record(processor) {
319
- this.recordingId = nanoid();
320
- const recordingProjectScope = processor.recordingProjectScope;
382
+ let unsubscribeAny;
383
+ let unsubscribeFinish;
321
384
  let settled = false;
322
385
  const finish = () => {
323
386
  if (settled)
324
387
  return;
325
388
  settled = true;
326
- unsubscribeAny();
327
- unsubscribeFinish();
389
+ unsubscribeAny?.();
390
+ unsubscribeFinish?.();
328
391
  emitDetached(this.#emitter, 'finish', {
329
392
  recording: this.getRecording(),
330
393
  });
331
394
  };
332
- const unsubscribeAny = processor.onAny((event, data) => {
333
- if (settled || event === 'finish') {
334
- return;
335
- }
336
- if (this.#includePartialOutputs === false && event === 'partialOutput') {
337
- return;
338
- }
339
- if (this.#includeTrace === false && event === 'trace') {
340
- return;
395
+ try {
396
+ this.recordingId = nanoid();
397
+ const recordingProjectScope = processor.recordingProjectScope;
398
+ unsubscribeAny = processor.onAny((event, data) => {
399
+ if (settled || event === 'finish') {
400
+ return;
401
+ }
402
+ if (this.#includePartialOutputs === false && event === 'partialOutput') {
403
+ return;
404
+ }
405
+ if (this.#includeTrace === false && event === 'trace') {
406
+ return;
407
+ }
408
+ const eventScope = getEventProjectScope(data);
409
+ if (eventScope !== undefined && eventScope !== recordingProjectScope) {
410
+ return;
411
+ }
412
+ if (!this.#captureDiscarded)
413
+ this.#append(toRecordedEvent(event, data));
414
+ });
415
+ unsubscribeFinish = processor.on('finish', finish);
416
+ }
417
+ catch (error) {
418
+ settled = true;
419
+ try {
420
+ unsubscribeAny?.();
341
421
  }
342
- const eventScope = getEventProjectScope(data);
343
- if (eventScope !== undefined && eventScope !== recordingProjectScope) {
344
- return;
422
+ catch {
423
+ /* Keep the original setup failure and release capture ownership. */
345
424
  }
346
- this.#events.push(toRecordedEvent(event, data));
347
- });
348
- const unsubscribeFinish = processor.on('finish', finish);
425
+ this.discard();
426
+ throw error;
427
+ }
349
428
  // Child processors have graph terminals but no root-level done/finish.
350
429
  // Their owner calls this after processGraph settles to make a standalone,
351
430
  // replayable recording without changing the live event stream.
352
431
  return (terminal) => {
353
432
  if (settled)
354
433
  return;
355
- if (terminal?.type === 'done')
356
- this.#events.push(toRecordedEvent('done', { results: terminal.results }));
357
- if (terminal?.type === 'error')
358
- this.#events.push(toRecordedEvent('error', { error: terminal.error }));
434
+ if (!this.#captureDiscarded && terminal?.type === 'done')
435
+ this.#append(toRecordedEvent('done', { results: terminal.results }));
436
+ if (!this.#captureDiscarded && terminal?.type === 'error')
437
+ this.#append(toRecordedEvent('error', { error: terminal.error }));
359
438
  finish();
360
439
  };
361
440
  }
@@ -393,9 +472,13 @@ export class ExecutionRecorder {
393
472
  return recorder;
394
473
  }
395
474
  serialize() {
475
+ if (this.#captureDiscarded)
476
+ throw new Error('Recording capture is unavailable.');
396
477
  return JSON.stringify(serializeToObject(this.getRecording()));
397
478
  }
398
479
  serializeStream() {
480
+ if (this.#captureDiscarded)
481
+ throw new Error('Recording capture is unavailable.');
399
482
  return stringifyJsonStream(serializeToObject(this.getRecording()));
400
483
  }
401
484
  }
@@ -1,2 +1,3 @@
1
1
  /** Lightweight entry point for file preparation without model/provider runtime initialization. */
2
2
  export { deserializeProject, deserializeGraph, deserializeDatasets, serializeProject, serializeGraph, serializeDatasets, } from './utils/serialization/serialization.js';
3
+ export { bindSharedReplayProjectId, serializeSharedReplayProject } from './utils/serialization/serialization_v4.js';
@@ -1,4 +1,5 @@
1
1
  import { mapValues } from 'lodash-es';
2
+ import stableStringify from 'safe-stable-stringify';
2
3
  import { normalizeSerializedLLMTemperatureData } from '../../model/chat-v2/llmChatV2NodeMigration.js';
3
4
  import { doubleCheckProject, isValidProjectStaticData } from './serializationUtils.js';
4
5
  import { entries } from '../typeSafety.js';
@@ -17,6 +18,27 @@ export function graphV4Deserializer(data) {
17
18
  return fromSerializedGraph(serializedGraph);
18
19
  }
19
20
  export function projectV4Serializer(project, attachedData) {
21
+ return wrapInYamlEnvelope(4, prepareSerializedProject(project, attachedData));
22
+ }
23
+ const replayProjectHeader = '{"version":4,"data":{"metadata":{"id":';
24
+ /** A v4 project with its ID at a known location, for rebinding a verified replay without re-encoding the graph. */
25
+ export function serializeSharedReplayProject(project, attachedData) {
26
+ const { metadata: { id, ...metadata }, ...data } = prepareSerializedProject(project, attachedData);
27
+ const metadataJson = stableStringify(metadata);
28
+ const dataJson = stableStringify(data);
29
+ // Numeric metadata keys are allowed and JSON.stringify would move them
30
+ // ahead of id. Write the fixed envelope once and keep the rest canonical.
31
+ const metadataTail = metadataJson === '{}' ? '}' : ',' + metadataJson.slice(1);
32
+ return replayProjectHeader + JSON.stringify(id) + metadataTail + ',' + dataJson.slice(1) + '}';
33
+ }
34
+ export function bindSharedReplayProjectId(snapshot, sourceId, recordingId) {
35
+ const sourceHeader = replayProjectHeader + JSON.stringify(sourceId);
36
+ const afterId = snapshot[sourceHeader.length];
37
+ if (!snapshot.startsWith(sourceHeader) || (afterId !== ',' && afterId !== '}'))
38
+ throw new Error('Shared replay project has an invalid source identity.');
39
+ return replayProjectHeader + JSON.stringify(recordingId) + snapshot.slice(sourceHeader.length);
40
+ }
41
+ function prepareSerializedProject(project, attachedData) {
20
42
  if (!isValidProjectStaticData(project.data)) {
21
43
  throw new Error('Project data must be a record of static-data strings');
22
44
  }
@@ -33,7 +55,7 @@ export function projectV4Serializer(project, attachedData) {
33
55
  path: undefined,
34
56
  },
35
57
  };
36
- return wrapInYamlEnvelope(4, toSerializedProject(filteredProject, attachedData));
58
+ return toSerializedProject(filteredProject, attachedData);
37
59
  }
38
60
  export function graphV4Serializer(graph) {
39
61
  return wrapInYamlEnvelope(4, toSerializedGraph(graph));
@@ -16,8 +16,8 @@
16
16
  * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17
17
  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18
18
  */
19
- // Copied straight from https://github.com/sindresorhus/fnv1a/blob/main/index.js
20
- // with types added
19
+ // Adapted from https://github.com/sindresorhus/fnv1a/blob/main/index.js
20
+ // with types and an equivalent 32-bit arithmetic fast path added.
21
21
  const FNV_PRIMES = {
22
22
  32: 16777619n,
23
23
  64: 1099511628211n,
@@ -36,6 +36,13 @@ const FNV_OFFSETS = {
36
36
  };
37
37
  const cachedEncoder = new globalThis.TextEncoder();
38
38
  function fnv1aUint8Array(uint8Array, size) {
39
+ if (size === 32) {
40
+ let hash = 2_166_136_261;
41
+ for (let index = 0; index < uint8Array.length; index++) {
42
+ hash = Math.imul(hash ^ uint8Array[index], 16_777_619);
43
+ }
44
+ return BigInt(hash >>> 0);
45
+ }
39
46
  const fnvPrime = FNV_PRIMES[size];
40
47
  let hash = FNV_OFFSETS[size];
41
48
  for (let index = 0; index < uint8Array.length; index++) {
@@ -8,6 +8,11 @@ export type ExecutionRecorderEvents = {
8
8
  export type ExecutionRecorderOptions = {
9
9
  includePartialOutputs?: boolean;
10
10
  includeTrace?: boolean;
11
+ /** Optional host accounting. Each recorder owns a separate capture lease. */
12
+ createCapturePolicy?: (recorder: ExecutionRecorder) => {
13
+ retain(event: RecordedEvents): boolean;
14
+ release(): void;
15
+ };
11
16
  };
12
17
  export type SocketRecordingOptions = {
13
18
  /** Record only the protocol messages belonging to one remote graph run. */
@@ -28,6 +33,9 @@ export declare class ExecutionRecorder {
28
33
  #private;
29
34
  recordingId: RecordingId | undefined;
30
35
  constructor(options?: ExecutionRecorderOptions);
36
+ get captureDiscarded(): boolean;
37
+ /** Release replay data, without cancelling the graph or its terminal listener. */
38
+ discard(): void;
31
39
  on: Emittery<ExecutionRecorderEvents>['on'];
32
40
  off: Emittery<ExecutionRecorderEvents>['off'];
33
41
  once: Emittery<ExecutionRecorderEvents>['once'];
@@ -1,2 +1,3 @@
1
1
  /** Lightweight entry point for file preparation without model/provider runtime initialization. */
2
2
  export { deserializeProject, deserializeGraph, deserializeDatasets, serializeProject, serializeGraph, serializeDatasets, type CombinedDataset, } from './utils/serialization/serialization.js';
3
+ export { bindSharedReplayProjectId, serializeSharedReplayProject } from './utils/serialization/serialization_v4.js';
@@ -4,6 +4,9 @@ import type { CombinedDataset } from './serialization.js';
4
4
  export declare function projectV4Deserializer(data: unknown): [Project, AttachedData];
5
5
  export declare function graphV4Deserializer(data: unknown): NodeGraph;
6
6
  export declare function projectV4Serializer(project: Project, attachedData?: AttachedData): unknown;
7
+ /** A v4 project with its ID at a known location, for rebinding a verified replay without re-encoding the graph. */
8
+ export declare function serializeSharedReplayProject(project: Project, attachedData: AttachedData): string;
9
+ export declare function bindSharedReplayProjectId(snapshot: string, sourceId: string, recordingId: string): string;
7
10
  export declare function graphV4Serializer(graph: NodeGraph): unknown;
8
11
  export declare function datasetV4Serializer(datasets: CombinedDataset[]): string;
9
12
  export declare function datasetV4Deserializer(serializedDatasets: string): CombinedDataset[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@valerypopoff/rivet2-core",
3
- "version": "2.32.0",
3
+ "version": "2.34.0",
4
4
  "license": "MIT",
5
5
  "main": "dist/cjs/bundle.cjs",
6
6
  "module": "dist/esm/index.js",