Repository navigation
Expand file tree
/
Copy pathalgo.ts
More file actions
1566 lines (1470 loc) · 48.8 KB
/
Copy pathalgo.ts
File metadata and controls
1566 lines (1470 loc) · 48.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable no-param-reassign */
import {
mergeConfigs,
patchConfig,
RunnableConfig,
} from "@langchain/core/runnables";
import { CallbackManagerForChainRun } from "@langchain/core/callbacks/manager";
import {
All,
BaseCheckpointSaver,
Checkpoint,
ReadonlyCheckpoint,
copyCheckpoint,
type PendingWrite,
type PendingWriteValue,
type WritesSortKey,
uuid5,
maxChannelVersion,
BaseStore,
CheckpointPendingWrite,
compareWritesSortKeys,
writesSortKey,
SendProtocol,
} from "@langchain/langgraph-checkpoint";
import {
BaseChannel,
createCheckpoint,
emptyChannels,
isDeltaChannel,
getOnlyChannels,
} from "../channels/base.js";
import { PregelNode } from "./read.js";
import { readChannel, readChannels } from "./io.js";
import {
_isSend,
_isSendInterface,
CONFIG_KEY_CHECKPOINT_MAP,
CHECKPOINT_NAMESPACE_SEPARATOR,
CONFIG_KEY_CHECKPOINTER,
CONFIG_KEY_READ,
CONFIG_KEY_TASK_ID,
CONFIG_KEY_SEND,
INTERRUPT,
RESERVED,
Send,
TAG_HIDDEN,
TASKS,
CHECKPOINT_NAMESPACE_END,
PUSH,
PULL,
RESUME,
NULL_TASK_ID,
CONFIG_KEY_SCRATCHPAD,
RETURN,
ERROR,
ERROR_SOURCE_NODE,
NO_WRITES,
CONFIG_KEY_PREVIOUS_STATE,
PREVIOUS,
CACHE_NS_WRITES,
CONFIG_KEY_RESUME_MAP,
CONFIG_KEY_NODE_ERROR,
START,
} from "../constants.js";
import {
Call,
isCall,
PregelExecutableTask,
PregelScratchpad,
PregelTaskDescription,
SimpleTaskPath,
TaskPath,
VariadicTaskPath,
} from "./types.js";
import { EmptyChannelError, InvalidUpdateError, NodeError } from "../errors.js";
import { getNullChannelVersion } from "./utils/index.js";
import { ExecutionInfo, LangGraphRunnableConfig } from "./runnable_types.js";
import { getRunnableForFunc } from "./call.js";
import { IterableReadableWritableStream } from "./stream.js";
import { XXH3 } from "../hash.js";
import { interruptId } from "../interrupt.js";
import { Topic } from "../channels/topic.js";
/**
* Construct a type with a set of properties K of type T
*/
export type StrRecord<K extends string, T> = {
[P in K]: T;
};
export type WritesProtocol<C = string> = {
name: string;
writes: PendingWrite<C>[];
triggers: string[];
path?: TaskPath;
};
export const increment = (current?: number) => {
return current !== undefined ? current + 1 : 1;
};
/**
* Serialize a task path to the string stored with its writes, matching
* Python's `task_path_str` byte for byte:
*
* - arrays (nested paths included) become `"~"` + their serialized elements
* joined by `", "` — so the empty path is `"~"`;
* - booleans format as ints (Python's `isinstance(x, int)` is true for
* `bool` there): `true` → `"0000000001"`, `false` → `"0000000000"`;
* - ints are zero-padded to 10 digits, sign-aware: `-1` → `"-000000001"`;
* - anything else (node names) is used as-is.
*
* This is the `taskPath` passed to `BaseCheckpointSaver.putWrites` and the
* first component of `writesSortKey`, so the stored string and its sort
* order are identical across the JS and Python runtimes.
*/
export function taskPathStr(path: unknown): string {
if (Array.isArray(path)) {
return `~${path.map(taskPathStr).join(", ")}`;
}
if (typeof path === "boolean") {
return path ? "0000000001" : "0000000000";
}
if (typeof path === "number") {
return path < 0
? `-${String(-path).padStart(9, "0")}`
: String(path).padStart(10, "0");
}
if (path === undefined || path === null) {
// Python serializes the empty tuple `()` — the path of input/null-task
// writes — to `"~"`.
return "~";
}
return String(path);
}
function triggersNextStep(
updatedChannels: Set<string>,
triggerToNodes: Record<string, string[]> | undefined
) {
if (triggerToNodes == null) return false;
for (const chan of updatedChannels) {
if (triggerToNodes[chan]) return true;
}
return false;
}
// Avoids unnecessary double iteration
function maxChannelMapVersion(
channelVersions: Record<string, number | string>
): number | string | undefined {
let maxVersion: number | string | undefined;
for (const chan in channelVersions) {
if (!Object.prototype.hasOwnProperty.call(channelVersions, chan)) continue;
if (maxVersion == null) {
maxVersion = channelVersions[chan];
} else {
maxVersion = maxChannelVersion(maxVersion, channelVersions[chan]);
}
}
return maxVersion;
}
export function shouldInterrupt<N extends PropertyKey, C extends PropertyKey>(
checkpoint: Checkpoint,
interruptNodes: All | N[],
tasks: PregelExecutableTask<N, C>[]
): boolean {
const nullVersion = getNullChannelVersion(checkpoint.channel_versions);
const seen = checkpoint.versions_seen[INTERRUPT] ?? {};
let anyChannelUpdated = false;
if (
(checkpoint.channel_versions[START] ?? nullVersion) >
(seen[START] ?? nullVersion)
) {
anyChannelUpdated = true;
} else {
for (const chan in checkpoint.channel_versions) {
if (
!Object.prototype.hasOwnProperty.call(checkpoint.channel_versions, chan)
)
continue;
if (checkpoint.channel_versions[chan] > (seen[chan] ?? nullVersion)) {
anyChannelUpdated = true;
break;
}
}
}
const anyTriggeredNodeInInterruptNodes = tasks.some((task) =>
interruptNodes === "*"
? !task.config?.tags?.includes(TAG_HIDDEN)
: interruptNodes.includes(task.name)
);
return anyChannelUpdated && anyTriggeredNodeInInterruptNodes;
}
export function _localRead<Cc extends Record<string, BaseChannel>>(
checkpoint: ReadonlyCheckpoint,
channels: Cc,
task: WritesProtocol<keyof Cc>,
select: Array<keyof Cc> | keyof Cc,
fresh: boolean = false
): Record<string, unknown> | unknown {
let updated = new Set<keyof Cc>();
if (!Array.isArray(select)) {
for (const [c] of task.writes) {
if (c === select) {
updated = new Set([c]);
break;
}
}
updated = updated || new Set();
} else {
updated = new Set(
select.filter((c) => task.writes.some(([key, _]) => key === c))
);
}
let values: Record<string, unknown>;
if (fresh && updated.size > 0) {
const localChannels = Object.fromEntries(
Object.entries(channels).filter(([k, _]) => updated.has(k as keyof Cc))
) as Partial<Cc>;
// DeltaChannels are omitted from `channel_values` by default (their state
// is reconstructed from ancestor writes via the saver). A local read has
// no saver, so snapshot every delta channel inline to round-trip its full
// live value through `emptyChannels`.
const channelsToSnapshot = new Set<string>();
for (const k in localChannels) {
if (!Object.prototype.hasOwnProperty.call(localChannels, k)) continue;
const ch = (localChannels as Record<string, BaseChannel>)[k];
if (isDeltaChannel(ch) && ch.isAvailable()) channelsToSnapshot.add(k);
}
const newCheckpoint = createCheckpoint(
checkpoint,
localChannels as Cc,
-1,
{
channelsToSnapshot,
}
);
const newChannels = emptyChannels(localChannels as Cc, newCheckpoint);
_applyWrites(
copyCheckpoint(newCheckpoint),
newChannels,
[task],
undefined,
undefined
);
values = readChannels({ ...channels, ...newChannels }, select);
} else {
values = readChannels(channels, select);
}
return values;
}
export function _localWrite(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
commit: (writes: [string, any][]) => any,
processes: Record<string, PregelNode>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
writes: [string, any][]
) {
for (const [chan, value] of writes) {
if ([PUSH, TASKS].includes(chan) && value != null) {
if (!_isSend(value)) {
throw new InvalidUpdateError(
`Invalid packet type, expected SendProtocol, got ${JSON.stringify(
value
)}`
);
}
if (!(value.node in processes)) {
throw new InvalidUpdateError(
`Invalid node name "${value.node}" in Send packet`
);
}
}
}
commit(writes);
}
const IGNORE = new Set<string | number | symbol>([
NO_WRITES,
PUSH,
RESUME,
INTERRUPT,
RETURN,
ERROR,
ERROR_SOURCE_NODE,
]);
const RESERVED_SET: ReadonlySet<string> = new Set(RESERVED);
export function _applyWrites<Cc extends Record<string, BaseChannel>>(
checkpoint: Checkpoint,
channels: Cc,
tasks: WritesProtocol<keyof Cc>[],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getNextVersion: ((version: any) => any) | undefined,
triggerToNodes: Record<string, string[]> | undefined
): Set<string> {
// Sort tasks on the serialized full task path, for deterministic order of
// update application. This is the same key every saver orders stored
// writes by (`writesSortKey`), so live execution and checkpointer replay
// cannot drift apart. Paths reaching here carry no task ids (call input
// paths are cut to `slice(0, 3) + true/false` in `_prepareSingleTask` and
// `acceptPush`), so this changes the live order only where the old
// 3-element array-coercion comparator disagreed with Python's serialized
// order (nested parent indices: it ordered `10` before `2`). Ties keep
// insertion order: the sort is stable and the key carries the default
// task-id/idx tie components, mirroring Python's `sorted`.
// Serialize each path once (taskPathStr allocates), then sort on the
// cached keys — the same precomputation the old comparator's pathCache did.
const sortKeys = new Map<WritesProtocol<keyof Cc>, WritesSortKey>();
for (const task of tasks) {
sortKeys.set(task, writesSortKey(taskPathStr(task.path)));
}
tasks.sort((a, b) =>
compareWritesSortKeys(sortKeys.get(a)!, sortKeys.get(b)!)
);
// Filter out non instances of BaseChannel
const onlyChannels = getOnlyChannels(channels);
// Single pass: update seen versions, check for triggers, collect channels to consume
let bumpStep = false;
const channelsToConsume = new Set<string>();
for (const task of tasks) {
if (task.triggers.length > 0) bumpStep = true;
checkpoint.versions_seen[task.name] ??= {};
for (const chan of task.triggers) {
if (chan in checkpoint.channel_versions) {
checkpoint.versions_seen[task.name][chan] =
checkpoint.channel_versions[chan];
}
if (!RESERVED_SET.has(chan)) {
channelsToConsume.add(chan);
}
}
}
// Find the highest version of all channels
let maxVersion = maxChannelMapVersion(checkpoint.channel_versions);
// Each version is minted once and shared by every channel it stamps, as in
// Python: a saver that adds a random fraction would otherwise give channels
// written together different versions, and updateState's "Ambiguous update"
// check compares them.
let consumedVersion: number | string | undefined;
for (const chan of channelsToConsume) {
if (chan in onlyChannels && onlyChannels[chan].consume()) {
if (getNextVersion !== undefined) {
consumedVersion ??= getNextVersion(maxVersion);
checkpoint.channel_versions[chan] = consumedVersion!;
}
}
}
// Group writes by channel
const pendingWritesByChannel = {} as Record<keyof Cc, PendingWriteValue[]>;
for (const task of tasks) {
for (const [chan, val] of task.writes) {
if (IGNORE.has(chan)) {
// do nothing
} else if (chan in onlyChannels) {
pendingWritesByChannel[chan] ??= [];
pendingWritesByChannel[chan].push(val);
}
}
}
// Note: no DeltaChannel-specific reordering here. Concurrent writes to a
// DeltaChannel apply in task-path order, exactly like every other channel
// and exactly like the savers replay them (`writesSortKey`); the task-id
// re-sort this replaces (langgraphjs#2544) made live order match a task-id
// replay instead, which permuted parallel writers checkpoint by checkpoint.
// Find the highest version of all channels
if (maxVersion != null && consumedVersion !== undefined) {
maxVersion = consumedVersion;
}
const nextVersion = getNextVersion?.(maxVersion);
const updatedChannels: Set<string> = new Set();
// Apply writes to channels
for (const [chan, vals] of Object.entries(pendingWritesByChannel)) {
if (chan in onlyChannels) {
const channel = onlyChannels[chan];
let updated;
try {
updated = channel.update(vals);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
if (e.name === InvalidUpdateError.unminifiable_name) {
const wrappedError = new InvalidUpdateError(
`Invalid update for channel "${chan}" with values ${JSON.stringify(
vals
)}: ${e.message}`
);
wrappedError.lc_error_code = e.lc_error_code;
throw wrappedError;
} else {
throw e;
}
}
if (updated && getNextVersion !== undefined) {
checkpoint.channel_versions[chan] = nextVersion;
// unavailable channels can't trigger tasks, so don't add them
if (channel.isAvailable()) updatedChannels.add(chan);
}
}
}
// Channels that weren't updated in this step are notified of a new step
if (bumpStep) {
for (const chan in onlyChannels) {
if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue;
const channel = onlyChannels[chan];
if (channel.isAvailable() && !updatedChannels.has(chan)) {
const updated = channel.update([]);
if (updated && getNextVersion !== undefined) {
checkpoint.channel_versions[chan] = nextVersion;
// unavailable channels can't trigger tasks, so don't add them
if (channel.isAvailable()) updatedChannels.add(chan);
}
}
}
}
// If this is (tentatively) the last superstep, notify all channels of finish
if (bumpStep && !triggersNextStep(updatedChannels, triggerToNodes)) {
for (const chan in onlyChannels) {
if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue;
const channel = onlyChannels[chan];
if (channel.finish() && getNextVersion !== undefined) {
checkpoint.channel_versions[chan] = nextVersion;
// unavailable channels can't trigger tasks, so don't add them
if (channel.isAvailable()) updatedChannels.add(chan);
}
}
}
return updatedChannels;
}
function* candidateNodes(
checkpoint: ReadonlyCheckpoint,
processes: StrRecord<string, PregelNode>,
extra: NextTaskExtraFields
) {
// This section is an optimization that allows which
// nodes will be active during the next step.
// When there's information about:
// 1. Which channels were updated in the previous step
// 2. Which nodes are triggered by which channels
// Then we can determine which nodes should be triggered
// in the next step without having to cycle through all nodes.
if (extra.updatedChannels != null && extra.triggerToNodes != null) {
const triggeredNodes = new Set<string>();
// Get all nodes that have triggers associated with an updated channel
for (const channel of extra.updatedChannels) {
const nodeIds = extra.triggerToNodes[channel];
for (const id of nodeIds ?? []) triggeredNodes.add(id);
}
// Sort the nodes to ensure deterministic order
yield* [...triggeredNodes].sort();
return;
}
// If there are no values in checkpoint, no need to run
// through all the PULL candidates
const isEmptyChannelVersions = (() => {
for (const chan in checkpoint.channel_versions) {
if (checkpoint.channel_versions[chan] !== null) return false;
}
return true;
})();
if (isEmptyChannelVersions) return;
for (const name in processes) {
if (!Object.prototype.hasOwnProperty.call(processes, name)) continue;
yield name;
}
}
/**
* Pre-indexed pending writes for O(1) lookups, avoiding repeated
* linear scans in _prepareSingleTask and _scratchpad.
*/
export type PendingWritesIndex = {
nullResume: unknown | undefined;
resumeByTaskId: Map<string, unknown[]>;
successfulWriteTaskIds: Set<string>;
};
/**
* Build an index over pendingWrites for O(1) lookups.
*
* @internal Exported for benchmarks and regression tests only.
*/
export function _indexPendingWrites(
pendingWrites: [string, string, unknown][] | undefined
): PendingWritesIndex {
let nullResume: unknown | undefined;
const resumeByTaskId = new Map<string, unknown[]>();
const successfulWriteTaskIds = new Set<string>();
if (pendingWrites) {
for (const [tid, chan, val] of pendingWrites) {
if (tid === NULL_TASK_ID && chan === RESUME && nullResume === undefined) {
nullResume = val;
}
if (chan === RESUME && tid !== NULL_TASK_ID) {
let arr = resumeByTaskId.get(tid);
if (!arr) {
arr = [];
resumeByTaskId.set(tid, arr);
}
arr.push(val);
}
if (chan !== ERROR) {
successfulWriteTaskIds.add(tid);
}
}
}
return { nullResume, resumeByTaskId, successfulWriteTaskIds };
}
export type NextTaskExtraFields = {
step: number;
isResuming?: boolean;
checkpointer?: BaseCheckpointSaver;
manager?: CallbackManagerForChainRun;
store?: BaseStore;
stream?: IterableReadableWritableStream;
triggerToNodes?: Record<string, string[]>;
updatedChannels?: Set<string>;
pendingWritesIndex?: PendingWritesIndex;
};
export type NextTaskExtraFieldsWithStore = NextTaskExtraFields & {
store?: BaseStore;
};
export type NextTaskExtraFieldsWithoutStore = NextTaskExtraFields & {
store?: never;
};
export function _prepareNextTasks<
Nn extends StrRecord<string, PregelNode>,
Cc extends StrRecord<string, BaseChannel>,
>(
checkpoint: ReadonlyCheckpoint,
pendingWrites: [string, string, unknown][] | undefined,
processes: Nn,
channels: Cc,
config: RunnableConfig,
forExecution: false,
extra: NextTaskExtraFieldsWithoutStore
): Record<string, PregelTaskDescription>;
export function _prepareNextTasks<
Nn extends StrRecord<string, PregelNode>,
Cc extends StrRecord<string, BaseChannel>,
>(
checkpoint: ReadonlyCheckpoint,
pendingWrites: [string, string, unknown][] | undefined,
processes: Nn,
channels: Cc,
config: RunnableConfig,
forExecution: true,
extra: NextTaskExtraFieldsWithStore
): Record<string, PregelExecutableTask<keyof Nn, keyof Cc>>;
/**
* Prepare the set of tasks that will make up the next Pregel step.
* This is the union of all PUSH tasks (Sends) and PULL tasks (nodes triggered
* by edges).
*/
export function _prepareNextTasks<
Nn extends StrRecord<string, PregelNode>,
Cc extends StrRecord<string, BaseChannel>,
>(
checkpoint: ReadonlyCheckpoint,
pendingWrites: [string, string, unknown][] | undefined,
processes: Nn,
channels: Cc,
config: RunnableConfig,
forExecution: boolean,
extra: NextTaskExtraFieldsWithStore | NextTaskExtraFieldsWithoutStore
):
| Record<string, PregelTaskDescription>
| Record<string, PregelExecutableTask<keyof Nn, keyof Cc>> {
const tasks:
| Record<string, PregelExecutableTask<keyof Nn, keyof Cc>>
| Record<string, PregelTaskDescription> = {};
// Pre-index pendingWrites once for O(1) lookups in _prepareSingleTask/_scratchpad
const indexedExtra: typeof extra = extra.pendingWritesIndex
? extra
: { ...extra, pendingWritesIndex: _indexPendingWrites(pendingWrites) };
// Consume pending tasks
const tasksChannel = channels[TASKS] as Topic<SendProtocol> | undefined;
if (tasksChannel?.isAvailable()) {
const len = tasksChannel.get().length;
for (let i = 0; i < len; i += 1) {
const task = _prepareSingleTask(
[PUSH, i],
checkpoint,
pendingWrites,
processes,
channels,
config,
forExecution,
indexedExtra
);
if (task !== undefined) {
tasks[task.id] = task;
}
}
}
// Check if any processes should be run in next step
// If so, prepare the values to be passed to them
for (const name of candidateNodes(checkpoint, processes, indexedExtra)) {
const task = _prepareSingleTask(
[PULL, name],
checkpoint,
pendingWrites,
processes,
channels,
config,
forExecution,
indexedExtra
);
if (task !== undefined) {
tasks[task.id] = task;
}
}
return tasks;
}
export function _prepareSingleTask<
Nn extends StrRecord<string, PregelNode>,
Cc extends StrRecord<string, BaseChannel>,
>(
taskPath: SimpleTaskPath,
checkpoint: ReadonlyCheckpoint,
pendingWrites: CheckpointPendingWrite[] | undefined,
processes: Nn,
channels: Cc,
config: RunnableConfig,
forExecution: false,
extra: NextTaskExtraFields
): PregelTaskDescription | undefined;
export function _prepareSingleTask<
Nn extends StrRecord<string, PregelNode>,
Cc extends StrRecord<string, BaseChannel>,
>(
taskPath: TaskPath,
checkpoint: ReadonlyCheckpoint,
pendingWrites: CheckpointPendingWrite[] | undefined,
processes: Nn,
channels: Cc,
config: RunnableConfig,
forExecution: true,
extra: NextTaskExtraFields
): PregelExecutableTask<keyof Nn, keyof Cc> | undefined;
export function _prepareSingleTask<
Nn extends StrRecord<string, PregelNode>,
Cc extends StrRecord<string, BaseChannel>,
>(
taskPath: TaskPath,
checkpoint: ReadonlyCheckpoint,
pendingWrites: CheckpointPendingWrite[] | undefined,
processes: Nn,
channels: Cc,
config: RunnableConfig,
forExecution: boolean,
extra: NextTaskExtraFieldsWithStore
): PregelTaskDescription | PregelExecutableTask<keyof Nn, keyof Cc> | undefined;
/**
* Prepares a single task for the next Pregel step, given a task path, which
* uniquely identifies a PUSH or PULL task within the graph.
*/
export function _prepareSingleTask<
Nn extends StrRecord<string, PregelNode>,
Cc extends StrRecord<string, BaseChannel>,
>(
taskPath: TaskPath,
checkpoint: ReadonlyCheckpoint,
pendingWrites: CheckpointPendingWrite[] | undefined,
processes: Nn,
channels: Cc,
config: LangGraphRunnableConfig,
forExecution: boolean,
extra: NextTaskExtraFields
):
| PregelTaskDescription
| PregelExecutableTask<keyof Nn, keyof Cc>
| undefined {
const { step, checkpointer, manager } = extra;
const configurable = config.configurable ?? {};
const parentNamespace = configurable.checkpoint_ns ?? "";
if (taskPath[0] === PUSH && isCall(taskPath[taskPath.length - 1])) {
const call = taskPath[taskPath.length - 1] as Call;
const proc = getRunnableForFunc(call.name, call.func);
const triggers = [PUSH];
const checkpointNamespace =
parentNamespace === ""
? call.name
: `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${call.name}`;
const id = uuid5(
JSON.stringify([
checkpointNamespace,
step.toString(),
call.name,
PUSH,
taskPath[1],
taskPath[2],
]),
checkpoint.id
);
const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${id}`;
// we append `true` to the task path to indicate that a call is being made
// so we should not return interrupts from this task (responsibility lies with the parent)
const outputTaskPath = [...taskPath.slice(0, 3), true] as VariadicTaskPath;
const metadata = {
langgraph_step: step,
langgraph_node: call.name,
langgraph_triggers: triggers,
langgraph_path: outputTaskPath,
langgraph_checkpoint_ns: taskCheckpointNamespace,
checkpoint_ns: taskCheckpointNamespace,
};
if (forExecution) {
const writes: [keyof Cc, unknown][] = [];
const executionInfo: ExecutionInfo = {
checkpointId: checkpoint.id,
checkpointNs: taskCheckpointNamespace,
taskId: id,
threadId: configurable.thread_id as string | undefined,
runId: config.runId != null ? String(config.runId) : undefined,
nodeAttempt: 1,
};
const task = {
name: call.name,
input: call.input,
proc,
writes,
config: {
...patchConfig(
mergeConfigs(config, {
metadata,
store: extra.store ?? config.store,
}),
{
runName: call.name,
callbacks: manager?.getChild(`graph:step:${step}`),
configurable: {
[CONFIG_KEY_TASK_ID]: id,
[CONFIG_KEY_SEND]: (writes_: PendingWrite[]) =>
_localWrite(
(items: PendingWrite<keyof Cc>[]) => writes.push(...items),
processes,
writes_
),
[CONFIG_KEY_READ]: (
select_: Array<keyof Cc> | keyof Cc,
fresh_: boolean = false
) =>
_localRead(
checkpoint,
channels,
{
name: call.name,
writes: writes as PendingWrite[],
triggers,
path: outputTaskPath,
},
select_,
fresh_
),
[CONFIG_KEY_CHECKPOINTER]:
checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER],
[CONFIG_KEY_CHECKPOINT_MAP]: {
...configurable[CONFIG_KEY_CHECKPOINT_MAP],
[parentNamespace]: checkpoint.id,
},
[CONFIG_KEY_SCRATCHPAD]: _scratchpad({
pendingWrites: pendingWrites ?? [],
taskId: id,
currentTaskInput: call.input,
resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP],
taskCheckpointNamespace,
pendingWritesIndex: extra.pendingWritesIndex,
}),
[CONFIG_KEY_PREVIOUS_STATE]:
checkpoint.channel_values[PREVIOUS],
checkpoint_id: undefined,
checkpoint_ns: taskCheckpointNamespace,
},
}
),
executionInfo,
},
triggers,
retry_policy: call.retry,
cache_key: call.cache
? {
key: XXH3((call.cache.keyFunc ?? JSON.stringify)([call.input])),
ns: [CACHE_NS_WRITES, call.name ?? "__dynamic__"],
ttl: call.cache.ttl,
}
: undefined,
id,
path: outputTaskPath,
writers: [],
timeout: call.timeout,
} satisfies PregelExecutableTask<keyof Nn, keyof Cc>;
return task;
} else {
return {
id,
name: call.name,
interrupts: [],
path: outputTaskPath,
};
}
} else if (taskPath[0] === PUSH) {
const index =
typeof taskPath[1] === "number"
? taskPath[1]
: parseInt(taskPath[1] as string, 10);
if (!channels[TASKS]?.isAvailable()) {
return undefined;
}
const sends = channels[TASKS].get() as SendProtocol[];
if (index < 0 || index >= sends.length) {
return undefined;
}
const packet =
_isSendInterface(sends[index]) && !_isSend(sends[index])
? new Send(
sends[index].node,
sends[index].args,
sends[index].timeout !== undefined
? { timeout: sends[index].timeout }
: undefined
)
: sends[index];
if (!_isSendInterface(packet)) {
console.warn(
`Ignoring invalid packet ${JSON.stringify(packet)} in pending sends.`
);
return undefined;
}
if (!(packet.node in processes)) {
console.warn(
`Ignoring unknown node name ${packet.node} in pending sends.`
);
return undefined;
}
const triggers = [PUSH];
const checkpointNamespace =
parentNamespace === ""
? packet.node
: `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${packet.node}`;
const taskId = uuid5(
JSON.stringify([
checkpointNamespace,
step.toString(),
packet.node,
PUSH,
index.toString(),
]),
checkpoint.id
);
const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${taskId}`;
// We append `false` to the task path to indicate that a call is not being
// made, so we should return interrupts from this task — matching Python's
// `(PUSH, idx, False)`. One translated path serves the executable task,
// the description, the metadata, and the local-read view.
const translatedTaskPath = [
...taskPath.slice(0, 3),
false,
] as VariadicTaskPath;
let metadata = {
langgraph_step: step,
langgraph_node: packet.node,
langgraph_triggers: triggers,
langgraph_path: translatedTaskPath,
langgraph_checkpoint_ns: taskCheckpointNamespace,
checkpoint_ns: taskCheckpointNamespace,
};
if (forExecution) {
const proc = processes[packet.node];
const node = proc.getNode();
if (node !== undefined) {
if (proc.metadata !== undefined) {
metadata = { ...metadata, ...proc.metadata };
}
const writes: [keyof Cc, unknown][] = [];
const executionInfo: ExecutionInfo = {
checkpointId: checkpoint.id,
checkpointNs: taskCheckpointNamespace,
taskId,
threadId: configurable.thread_id as string | undefined,
runId: config.runId != null ? String(config.runId) : undefined,
nodeAttempt: 1,
};
return {
name: packet.node,
input: packet.args,
proc: node,
subgraphs: proc.subgraphs,
writes,
config: {
...patchConfig(
mergeConfigs(config, {
metadata,
tags: proc.tags,
store: extra.store ?? config.store,
}),
{
runName: packet.node,
callbacks: manager?.getChild(`graph:step:${step}`),
configurable: {
[CONFIG_KEY_TASK_ID]: taskId,
[CONFIG_KEY_SEND]: (writes_: PendingWrite[]) =>
_localWrite(
(items: PendingWrite<keyof Cc>[]) =>
writes.push(...items),
processes,
writes_
),
[CONFIG_KEY_READ]: (
select_: Array<keyof Cc> | keyof Cc,
fresh_: boolean = false
) =>
_localRead(
checkpoint,
channels,
{
name: packet.node,
writes: writes as PendingWrite[],
triggers,
path: translatedTaskPath,
},
select_,
fresh_
),
[CONFIG_KEY_CHECKPOINTER]:
checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER],
[CONFIG_KEY_CHECKPOINT_MAP]: {
...configurable[CONFIG_KEY_CHECKPOINT_MAP],
[parentNamespace]: checkpoint.id,
},
[CONFIG_KEY_SCRATCHPAD]: _scratchpad({
pendingWrites: pendingWrites ?? [],
taskId,
currentTaskInput: packet.args,
resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP],
taskCheckpointNamespace,
pendingWritesIndex: extra.pendingWritesIndex,
}),
[CONFIG_KEY_PREVIOUS_STATE]:
checkpoint.channel_values[PREVIOUS],