periplon 0.2.0

Rust SDK for building multi-agent AI workflows and automation
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
# DSL Loop Patterns Guide

**Version:** 1.0
**Date:** 2025-10-19
**Status:** Production Ready

---

## Table of Contents

1. [Overview]#overview
2. [Loop Pattern Types]#loop-pattern-types
3. [Collection Sources]#collection-sources
4. [Loop Control Features]#loop-control-features
5. [Variable Substitution]#variable-substitution
6. [Best Practices]#best-practices
7. [Common Pitfalls]#common-pitfalls
8. [Performance Considerations]#performance-considerations
9. [Security Considerations]#security-considerations

---

## Overview

The DSL loop system provides powerful iteration capabilities for multi-agent workflows. Loops enable processing collections, polling for conditions, retrying operations, and executing repeated tasks.

### Key Capabilities

- **Collection Iteration** - Process arrays, files, ranges, HTTP APIs
- **Conditional Loops** - While/until patterns for dynamic workflows
- **Repeat Patterns** - Count-based iteration for batch operations
- **Parallel Execution** - Concurrent iteration with concurrency limits
- **State Persistence** - Checkpoint and resume interrupted loops
- **Loop Control** - Break/continue, timeouts, result collection
- **Variable Substitution** - Use loop variables in task definitions

### When to Use Loops

**Use loops when you need to:**
- Process multiple items from a collection
- Poll for a condition to become true
- Retry an operation with backoff
- Execute a task multiple times
- Batch process data
- Iterate over API results

**Don't use loops when:**
- Single task execution is sufficient
- Dependencies can be modeled as task graph
- Operation doesn't involve iteration

---

## Loop Pattern Types

### 1. ForEach Loop

**Purpose:** Iterate over a collection of items.

**YAML Syntax:**
```yaml
tasks:
  process_items:
    description: "Process {{item.name}}"
    agent: "processor"
    loop:
      type: for_each
      collection:
        source: inline
        items: ["item1", "item2", "item3"]
      iterator: "item"
      parallel: false  # Optional: enable parallel execution
      max_parallel: 3  # Optional: limit concurrent iterations
    loop_control:
      collect_results: true  # Optional: collect iteration outputs
      result_key: "processed_items"  # Optional: key to store results
```

**When to Use:**
- Processing files in a directory
- Handling multiple entities from a database query
- Batch processing API results
- Data transformation pipelines
- Multi-step workflows per item

**Execution Modes:**

**Sequential (default):**
```yaml
loop:
  type: for_each
  collection:
    source: inline
    items: [1, 2, 3]
  iterator: "num"
  parallel: false  # Execute one at a time
```

**Parallel:**
```yaml
loop:
  type: for_each
  collection:
    source: inline
    items: [1, 2, 3]
  iterator: "num"
  parallel: true
  max_parallel: 2  # At most 2 concurrent iterations
```

**Example: Process GitHub Repositories**
```yaml
tasks:
  analyze_repos:
    description: "Analyzing {{repo.name}}"
    agent: "analyzer"
    loop:
      type: for_each
      collection:
        source: http
        url: "https://api.github.com/users/octocat/repos"
        headers:
          Accept: "application/vnd.github.v3+json"
        format: json
      iterator: "repo"
    loop_control:
      collect_results: true
      result_key: "analysis_results"
```

---

### 2. While Loop

**Purpose:** Execute while a condition is true (condition checked BEFORE each iteration).

**YAML Syntax:**
```yaml
tasks:
  poll_status:
    description: "Checking status (iteration {{iteration}})"
    agent: "checker"
    loop:
      type: while
      condition:
        type: state_equals
        key: "job_complete"
        value: false
      max_iterations: 100  # Safety limit
      iteration_variable: "iteration"  # Optional: track iteration number
      delay_between_secs: 5  # Optional: wait between iterations
    loop_control:
      timeout_secs: 300  # Optional: 5 minute timeout
```

**When to Use:**
- Polling for job completion
- Waiting for external condition
- Event-driven workflows
- Dynamic iteration based on runtime state

**Safety Features:**
- **max_iterations:** Required safety limit
- **timeout_secs:** Optional overall timeout
- **delay_between_secs:** Optional delay to avoid tight loops

**Example: Poll API Until Ready**
```yaml
tasks:
  wait_for_deployment:
    description: "Checking deployment status (attempt {{iteration}})"
    agent: "poller"
    loop:
      type: while
      condition:
        type: state_equals
        key: "deployment_ready"
        value: false
      max_iterations: 60
      iteration_variable: "iteration"
      delay_between_secs: 10  # Check every 10 seconds
    loop_control:
      timeout_secs: 600  # 10 minute max
```

---

### 3. RepeatUntil Loop

**Purpose:** Execute until a condition is true (condition checked AFTER each iteration).

**YAML Syntax:**
```yaml
tasks:
  retry_operation:
    description: "Attempting operation (iteration {{iteration}})"
    agent: "worker"
    loop:
      type: repeat_until
      condition:
        type: state_equals
        key: "operation_success"
        value: true
      min_iterations: 1  # Optional: minimum iterations
      max_iterations: 10  # Required: safety limit
      iteration_variable: "iteration"  # Optional
      delay_between_secs: 2  # Optional: exponential backoff
    loop_control:
      timeout_secs: 60
```

**When to Use:**
- Retry operations with condition check
- Operations that must run at least once
- Exponential backoff retry logic
- Validation loops (do-while pattern)

**Difference from While:**
- **While:** Checks condition BEFORE iteration (may never execute)
- **RepeatUntil:** Checks condition AFTER iteration (executes at least once)

**Example: Retry API Call**
```yaml
tasks:
  fetch_data_with_retry:
    description: "Fetching data (attempt {{iteration}})"
    agent: "fetcher"
    loop:
      type: repeat_until
      condition:
        type: state_equals
        key: "fetch_success"
        value: true
      min_iterations: 1
      max_iterations: 5
      iteration_variable: "iteration"
      delay_between_secs: 2  # 2, 4, 8, 16 seconds (if using exponential)
    loop_control:
      timeout_secs: 60
```

---

### 4. Repeat Loop

**Purpose:** Execute a fixed number of iterations.

**YAML Syntax:**
```yaml
tasks:
  batch_process:
    description: "Processing batch {{batch_num}}"
    agent: "processor"
    loop:
      type: repeat
      count: 10  # Execute 10 times
      iterator: "batch_num"  # Optional: variable for iteration number
      parallel: false  # Optional: enable parallel execution
      max_parallel: 3  # Optional: limit concurrency
```

**When to Use:**
- Fixed number of iterations
- Batch processing with known count
- Stress testing (run N times)
- Parallel task execution

**Execution Modes:**

**Sequential:**
```yaml
loop:
  type: repeat
  count: 5
  iterator: "iteration"
  parallel: false
```

**Parallel:**
```yaml
loop:
  type: repeat
  count: 10
  iterator: "iteration"
  parallel: true
  max_parallel: 5
```

**Example: Parallel Batch Processing**
```yaml
tasks:
  process_batches:
    description: "Processing batch {{batch}}/10"
    agent: "processor"
    loop:
      type: repeat
      count: 10
      iterator: "batch"
      parallel: true
      max_parallel: 3  # Process 3 batches concurrently
    loop_control:
      collect_results: true
      result_key: "batch_results"
```

---

## Collection Sources

### 1. Inline Collections

**Hardcoded arrays in YAML.**

```yaml
collection:
  source: inline
  items: ["file1.txt", "file2.txt", "file3.txt"]
```

**Use When:**
- Small, static lists
- Configuration-driven workflows
- Testing and examples

---

### 2. State Collections

**Arrays stored in workflow state.**

```yaml
collection:
  source: state
  key: "file_list"  # State key containing array
```

**Use When:**
- Dynamic collections from previous tasks
- Results from earlier iterations
- Runtime-determined items

**Example:**
```yaml
tasks:
  fetch_files:
    description: "List files"
    agent: "lister"
    # This task stores results in state["file_list"]

  process_files:
    description: "Process {{file}}"
    agent: "processor"
    depends_on: [fetch_files]
    loop:
      type: for_each
      collection:
        source: state
        key: "file_list"
      iterator: "file"
```

---

### 3. File Collections

**Arrays loaded from files.**

**JSON:**
```yaml
collection:
  source: file
  path: "data/items.json"
  format: json
```

**JSON Lines (one JSON object per line):**
```yaml
collection:
  source: file
  path: "data/items.jsonl"
  format: json_lines
```

**CSV:**
```yaml
collection:
  source: file
  path: "data/items.csv"
  format: csv  # Each row becomes an array
```

**Plain text lines:**
```yaml
collection:
  source: file
  path: "data/urls.txt"
  format: lines  # Each line becomes a string
```

**Use When:**
- Large datasets
- External data sources
- Batch jobs with input files

---

### 4. Range Collections

**Numeric ranges.**

```yaml
collection:
  source: range
  start: 0
  end: 100
  step: 1  # Optional, default: 1
```

**Use When:**
- Numeric iteration (0 to N)
- Batch number generation
- Pagination (process pages 1-10)

**Example: Process Pages**
```yaml
loop:
  type: for_each
  collection:
    source: range
    start: 1
    end: 11  # Pages 1-10
    step: 1
  iterator: "page"
```

---

### 5. HTTP Collections

**Arrays fetched from HTTP APIs.**

**Basic GET:**
```yaml
collection:
  source: http
  url: "https://api.example.com/items"
  method: "GET"
  format: json
```

**With Headers:**
```yaml
collection:
  source: http
  url: "https://api.example.com/items"
  method: "GET"
  headers:
    Authorization: "Bearer token123"
    Accept: "application/json"
  format: json
```

**With JSON Path:**
```yaml
collection:
  source: http
  url: "https://api.example.com/data"
  method: "GET"
  format: json
  json_path: "data.items"  # Extract nested array
```

**POST Request:**
```yaml
collection:
  source: http
  url: "https://api.example.com/search"
  method: "POST"
  headers:
    Content-Type: "application/json"
  body: '{"query": "rust programming"}'
  format: json
```

**Use When:**
- REST API results
- External data sources
- Dynamic collections from APIs
- Paginated API responses

---

## Loop Control Features

### 1. Break Condition

**Exit loop early when condition is met.**

```yaml
loop_control:
  break_condition:
    type: state_equals
    key: "error_found"
    value: true
```

**Evaluated:** AFTER each iteration
**Effect:** Stops loop immediately

**Example:**
```yaml
tasks:
  scan_files:
    description: "Scanning {{file}}"
    agent: "scanner"
    loop:
      type: for_each
      collection:
        source: state
        key: "files"
      iterator: "file"
    loop_control:
      break_condition:
        type: state_equals
        key: "malware_found"
        value: true
```

---

### 2. Continue Condition

**Skip iteration when condition is met.**

```yaml
loop_control:
  continue_condition:
    type: state_equals
    key: "skip_this"
    value: true
```

**Evaluated:** BEFORE each iteration
**Effect:** Skips current iteration, continues to next

**Example:**
```yaml
tasks:
  process_files:
    description: "Processing {{file}}"
    agent: "processor"
    loop:
      type: for_each
      collection:
        source: state
        key: "files"
      iterator: "file"
    loop_control:
      continue_condition:
        type: state_equals
        key: "file_processed"
        value: true  # Skip already processed files
```

---

### 3. Timeout

**Limit total loop execution time.**

```yaml
loop_control:
  timeout_secs: 300  # 5 minutes max
```

**Behavior:**
- Applies to entire loop
- Cancels current iteration on timeout
- Returns timeout error

**Example:**
```yaml
tasks:
  poll_service:
    description: "Polling service"
    agent: "poller"
    loop:
      type: while
      condition:
        type: state_equals
        key: "service_ready"
        value: false
      max_iterations: 100
      delay_between_secs: 3
    loop_control:
      timeout_secs: 300  # Don't wait more than 5 minutes
```

---

### 4. Checkpoint Interval

**Save state periodically for resume capability.**

```yaml
loop_control:
  checkpoint_interval: 10  # Save every 10 iterations
```

**Behavior:**
- Saves state to disk after N iterations
- Enables resume after interruption
- Skips completed iterations on resume

**Example:**
```yaml
tasks:
  process_large_batch:
    description: "Processing item {{item}}"
    agent: "processor"
    loop:
      type: for_each
      collection:
        source: range
        start: 0
        end: 10000
        step: 1
      iterator: "item"
    loop_control:
      checkpoint_interval: 100  # Checkpoint every 100 items
      collect_results: true
      result_key: "processed_items"
```

---

### 5. Result Collection

**Collect outputs from iterations.**

```yaml
loop_control:
  collect_results: true
  result_key: "my_results"  # Store in state["my_results"]
```

**Behavior:**
- Collects iteration outputs into array
- Stores in workflow state under result_key
- Available to subsequent tasks

**Example:**
```yaml
tasks:
  transform_data:
    description: "Transforming {{item}}"
    agent: "transformer"
    loop:
      type: for_each
      collection:
        source: state
        key: "raw_data"
      iterator: "item"
    loop_control:
      collect_results: true
      result_key: "transformed_data"

  analyze_results:
    description: "Analyze transformed data"
    agent: "analyzer"
    depends_on: [transform_data]
    # Can access state["transformed_data"]
```

---

## Variable Substitution

### Iteration Variables

Loop variables can be used in task fields:

**In Description:**
```yaml
description: "Processing {{item.name}} ({{iteration}}/{{total}})"
```

**In Output Path:**
```yaml
output: "results/{{item.id}}.json"
```

**In Conditions:**
```yaml
condition:
  type: state_equals
  key: "current_{{iterator}}_status"
  value: "ready"
```

### Available Variables

**ForEach Loops:**
- `{{iterator}}` - Current item value
- `{{iteration}}` - Current iteration number (0-based)
- `{{item.field}}` - Object field access (if item is object)

**Repeat Loops:**
- `{{iterator}}` - Current iteration number
- `{{iteration}}` - Same as iterator

**While/RepeatUntil Loops:**
- `{{iteration}}` - Current iteration number (if iteration_variable set)

### Examples

**Process files with numbering:**
```yaml
tasks:
  process_file:
    description: "Processing file {{file}} ({{iteration}}/{{total}})"
    agent: "processor"
    output: "results/file_{{iteration}}.json"
    loop:
      type: for_each
      collection:
        source: inline
        items: ["a.txt", "b.txt", "c.txt"]
      iterator: "file"
```

**Access nested object fields:**
```yaml
tasks:
  process_user:
    description: "Processing user {{user.name}} (ID: {{user.id}})"
    agent: "processor"
    loop:
      type: for_each
      collection:
        source: http
        url: "https://api.example.com/users"
        format: json
      iterator: "user"
```

---

## Best Practices

### 1. Always Set Safety Limits

**DO:**
```yaml
loop:
  type: while
  condition: ...
  max_iterations: 100  # ALWAYS set max
  delay_between_secs: 5
loop_control:
  timeout_secs: 600  # Add timeout for extra safety
```

**DON'T:**
```yaml
loop:
  type: while
  condition: ...
  # Missing max_iterations - UNSAFE!
```

---

### 2. Use Checkpoints for Long Loops

**DO:**
```yaml
loop:
  type: for_each
  collection:
    source: range
    start: 0
    end: 10000
  iterator: "item"
loop_control:
  checkpoint_interval: 100  # Save every 100 iterations
```

**DON'T:**
```yaml
loop:
  type: for_each
  collection:
    source: range
    start: 0
    end: 10000
  iterator: "item"
  # No checkpointing - all progress lost on failure
```

---

### 3. Limit Parallel Concurrency

**DO:**
```yaml
loop:
  type: for_each
  collection: ...
  iterator: "item"
  parallel: true
  max_parallel: 5  # Reasonable limit
```

**DON'T:**
```yaml
loop:
  type: for_each
  collection: ...  # 1000 items
  iterator: "item"
  parallel: true
  # No max_parallel - may spawn 1000 concurrent tasks!
```

---

### 4. Add Delays to Polling Loops

**DO:**
```yaml
loop:
  type: while
  condition: ...
  max_iterations: 60
  delay_between_secs: 5  # Check every 5 seconds
```

**DON'T:**
```yaml
loop:
  type: while
  condition: ...
  max_iterations: 1000
  # No delay - tight loop, wastes resources
```

---

### 5. Collect Results When Needed

**DO:**
```yaml
loop_control:
  collect_results: true  # Need results for next task
  result_key: "outputs"
```

**DON'T:**
```yaml
loop_control:
  collect_results: true  # Results never used
  # Wastes memory collecting unnecessary data
```

---

### 6. Use Appropriate Collection Sources

**DO:**
```yaml
# Use HTTP for dynamic API data
collection:
  source: http
  url: "https://api.example.com/items"

# Use state for previous task results
collection:
  source: state
  key: "previous_results"
```

**DON'T:**
```yaml
# Don't hardcode large collections
collection:
  source: inline
  items: [1, 2, 3, ... 1000]  # Use range or file instead!
```

---

## Common Pitfalls

### 1. Infinite Loops

**Problem:** While loop with condition that never becomes false.

**Example:**
```yaml
loop:
  type: while
  condition:
    type: state_equals
    key: "always_true"
    value: true
  max_iterations: 1000000  # Too high!
```

**Solution:** Set reasonable max_iterations and add timeout.

---

### 2. Resource Exhaustion

**Problem:** Unbounded parallel execution.

**Example:**
```yaml
loop:
  type: for_each
  collection:
    source: range
    start: 0
    end: 100000  # 100k items!
  iterator: "item"
  parallel: true  # All at once!
```

**Solution:** Always set max_parallel.

---

### 3. Missing Error Handling

**Problem:** Loop continues despite errors.

**Example:**
```yaml
loop:
  type: for_each
  collection: ...
  iterator: "item"
  # No break_condition for errors
```

**Solution:** Add break condition for critical errors.

---

### 4. Forgotten Checkpoints

**Problem:** Long loop loses all progress on failure.

**Example:**
```yaml
loop:
  type: for_each
  collection:
    source: range
    start: 0
    end: 10000
  iterator: "item"
  # No checkpoint_interval
```

**Solution:** Add checkpoint_interval for loops > 100 iterations.

---

### 5. Tight Polling Loops

**Problem:** Polling without delay wastes resources.

**Example:**
```yaml
loop:
  type: while
  condition: ...
  max_iterations: 10000
  # No delay_between_secs!
```

**Solution:** Always add delay_between_secs for while/repeat_until.

---

## Performance Considerations

### 1. Parallel vs Sequential

**Sequential (default):**
- One iteration at a time
- Predictable resource usage
- Maintains order

**Parallel:**
- Multiple iterations concurrently
- Faster for I/O-bound tasks
- Higher resource usage
- No guaranteed order

**Choose Parallel When:**
- Iterations are independent
- I/O-bound operations (API calls, file I/O)
- Time is critical
- Resources are available

**Choose Sequential When:**
- Order matters
- Shared state mutations
- Resource-constrained
- Debugging

---

### 2. Collection Size Limits

**Hard Limits:**
- Max collection size: 100,000 items
- Max iterations per loop: 10,000
- Max parallel iterations: 100

**Recommendations:**
- Keep collections < 1,000 items for best performance
- Use pagination for larger datasets
- Split large jobs into multiple workflows

---

### 3. Checkpoint Frequency

**Checkpoint Interval Guidelines:**
- **Fast iterations (<1s):** Every 100-1000 iterations
- **Medium iterations (1-10s):** Every 10-100 iterations
- **Slow iterations (>10s):** Every 1-10 iterations

**Trade-offs:**
- More frequent: Better resume granularity, more I/O overhead
- Less frequent: Lower overhead, more lost work on failure

---

### 4. State Collection Memory

**Memory Usage:**
- Each collected result stored in memory
- Large results accumulate quickly

**Best Practices:**
- Only collect results when needed
- Consider streaming for large datasets
- Clear state after processing

---

## Security Considerations

### 1. Loop Bombs

**Definition:** Malicious loops designed to exhaust resources.

**Protection:**
- Hard-coded MAX_LOOP_ITERATIONS (10,000)
- Hard-coded MAX_COLLECTION_SIZE (100,000)
- Required max_iterations for while/repeat_until
- Timeout enforcement

**Example Blocked Loop Bomb:**
```yaml
loop:
  type: repeat
  count: 999999999  # Rejected - exceeds MAX_LOOP_ITERATIONS
```

---

### 2. API Rate Limiting

**Problem:** HTTP collections can trigger rate limits.

**Solutions:**
- Add delays between iterations
- Use max_parallel to limit concurrency
- Implement backoff strategies
- Cache responses

**Example:**
```yaml
loop:
  type: for_each
  collection:
    source: http
    url: "https://api.example.com/items"
  iterator: "item"
  parallel: true
  max_parallel: 2  # Respect API rate limits
loop_control:
  timeout_secs: 600
```

---

### 3. Input Validation

**Always validate:**
- Collection sources (URLs, file paths)
- Loop parameters (counts, iterations)
- User-provided data in collections

**Validation Checks:**
- URL must start with http:// or https://
- File paths must be safe (no directory traversal)
- Counts must be within limits
- Methods must be whitelisted

---

## Summary

The DSL loop system provides powerful, safe, and flexible iteration capabilities:

✅ **Four loop patterns** - ForEach, While, RepeatUntil, Repeat
✅ **Five collection sources** - Inline, State, File, Range, HTTP
✅ **Advanced control** - Break, continue, timeout, checkpoints
✅ **Parallel execution** - Concurrent iterations with limits
✅ **State persistence** - Resume capability
✅ **Safety features** - Resource limits, timeouts, validation

Follow best practices and avoid common pitfalls for production-ready workflows!

---

**Last Updated:** 2025-10-19
**Version:** 1.0
**Status:** ✅ Production Ready