Download all docs
apps

Loop

The iteration primitive of the actor layer — wrap any element in a loop and it runs once per item in a collection or once per step in a range, sequentially or in parallel, with concurrency caps, early-exit conditions, and per-iteration error handling so a batch can finish even when individual items fail.

Working with it

Selecting a Loop reveals its settings in the properties panel; it has no dedicated full-screen workbench.

How it appears

The same element type rendered as a definition, a circle instance, and a live workspace card.

Lp
type

Loop

Iterate over collections or repeat until condition

appsatomdefinition

When to use / not

When to use

  • Fanning a body element out across a collection — validate every order, send a batch of notifications, or transform each record in a list.
  • Running independent work concurrently with a bounded blast radius — parallel mode up to max_concurrency, instead of issuing the calls one at a time.
  • Walking a numeric range, e.g. paginating an API page-by-page in sequential mode and stopping early with a break_condition once there's no more data.
  • Processing a batch where some items are expected to fail — collect only the successful results and abort if the failure rate crosses max_failures.

When not to use

  • Branching once on a single yes/no decision — that is the `condition` element, not a loop over one item.
  • Pausing or delaying before the next step — use the `wait` element rather than a loop that does nothing per iteration.
  • Invoking an element a single time — call that element directly; a loop only earns its keep when there is a collection or range to iterate.

Topology

Lives nested inside a parent element rather than standing alone — it is created in the context of its container.

Properties

itemsobject
Items to iterate over
modestring
Execution mode
max_concurrencyinteger
Max parallel iterations (only applies in parallel mode)
max_iterationsinteger
Safety limit — loop stops after this many iterations regardless of items

Capabilities

Defined for this element
  • Observe

Operations

  • activityGET
  • attachmentsGET
  • batch_statsGET
  • breakPOST
  • composePOST
  • contextGET
  • continue_loopPOST
  • createPOST
  • deleteDELETE
  • disablePOST
  • enablePOST
  • executePOST
  • export_bundleGET
  • getGET
  • import_bundlePOST
  • intentionGET
  • loop_statusGET
  • promotePOST
  • readmeGET
  • readme_updatePOST
  • remove-modifierPOST
  • restorePOST
  • schemaGET
  • sourceGET
  • source_branchesGET
  • source_promotePOST
  • source_repairPOST
  • source_statusGET
  • source_validatePOST
  • statsGET
  • treeGET
  • updatePATCH
  • update_metaPATCH
  • versionGET

Ports

Inputs

  • itemsrequest
  • resultrequest

Composition

Uses
Attaches
Referenced by

Errors / when it fails

Consider setting max_concurrency for parallel loops
Range iteration requires both start and end values
Range step cannot be zero
Fails unless: items.step != 0

Validation rules

  • Large iteration limit (>10k) - ensure this is intentional
  • High concurrency (>50) may overwhelm downstream services
  • on_error=continue without max_failures may ignore all errors
  • Collecting results from >1000 iterations may use significant memory

Loop (loop)

Category: apps | Form: | Symbol: Lp

Iterate over collections or repeat until condition

Iterates over a collection, calling a body element for each item. Set spec.body_ref to the target element’s slug (required — omitting it causes a 400 error). Set spec.max_iterations (default: 1000) as a safety limit. Execute operation requires items:[] array in input. Set concurrency (default: 1) for parallel execution and continue_on_error: true to keep going after failures. Returns loop_run_id for status tracking via loop_status. Use break operation with loop_run_id to stop early. Run state is stored in spec.loop_runs (max 50 records retained). Common mistake: forgetting to set spec.body_ref before executing.

Guide

Iterate over collections or repeat until condition

What It Does

Loop executes a body element repeatedly — either once per item in a collection, once per integer in a range, or until a CEL break condition becomes true. It supports both sequential and parallel execution modes, configurable concurrency limits, early exit, and per-iteration error handling. Loop is the iteration primitive of the actor layer, typically wrapping a function or a nested flow to process batches of data.

Element Definition

PropertyValue
Typeloop
Categoryapps
Formatom
Symbolloop / #F59E0B

Properties

FieldTypeDefaultDescription
body_refstringReference to the element to execute in each iteration
itemsobjectItems to iterate over (required). Either a CEL expression returning an array, or a range object {start, end, step}
modestring (enum)sequentialExecution mode: sequential or parallel
max_concurrencyinteger10Maximum parallel iterations (only applies in parallel mode)
max_iterationsinteger1000Safety cap on total iterations
timeout_msinteger300000Overall loop execution timeout in milliseconds
break_conditionstringCEL expression evaluated after each iteration — loop exits early when true
continue_conditionstringCEL expression evaluated before each iteration — iteration is skipped when false
error_handling.on_errorstring (enum)failBehavior on iteration error: fail, continue, or break
error_handling.max_failuresintegerMaximum number of failures before stopping (regardless of on_error)
result.collectbooleantrueCollect iteration outputs into the results array
result.filterstringCEL expression to filter which iteration results are included

Ports

DirectionPortTypeRequiredDescription
InputitemsrequestYesArray to iterate or range {start, end, step}
OutputresultrequestYesLoop result: results array, iterations_count, break_triggered

Topology

  • Lives in: apps/automation/loop/ repository
  • Referenced by: projects
  • Accepts modifiers: rate-limit, requirements
  • Uses resources: variable

Capabilities

CapabilityDescription
iterationFor-each and range loops
parallelParallel iteration with configurable concurrency
early-exitBreak condition support for early termination

Error Codes

CodeClassRetryableDescription
LOOP_MAX_ITERATIONSlimitNoExceeded the max_iterations safety limit
LOOP_ITERATION_FAILEDinternalNoAn iteration failed (when on_error is fail)

Quick Start

Creating via API

Create a loop element inside a project:

POST /api/{circle}/{project}/
Content-Type: application/json

{
  "element_type": "loop",
  "slug": "process-orders",
  "name": "Process Orders",
  "spec": {
    "mode": "parallel",
    "max_concurrency": 5,
    "items": "input.orders",
    "body_ref": "validate-order",
    "error_handling": {
      "on_error": "continue"
    }
  }
}

Basic Usage

Invoke the loop with a list of items:

POST /api/{circle}/{project}/process-orders/ops/invoke
Content-Type: application/json

{
  "items": [
    {"id": "ord-1", "amount": 99.00},
    {"id": "ord-2", "amount": 149.50},
    {"id": "ord-3", "amount": 49.99}
  ]
}

Response:

{
  "results": [
    {"id": "ord-1", "status": "valid"},
    {"id": "ord-2", "status": "valid"},
    {"id": "ord-3", "status": "valid"}
  ],
  "iterations_count": 3,
  "break_triggered": false
}

Project Patterns

How Loop Fits Into Projects

Loop sits between a data-producing element (a function that fetches a list) and a data-consuming element (a function that processes each item). The body element receives a single item per iteration and returns a result per iteration. In sequential mode, each iteration completes before the next starts — use this for operations that must be ordered or when the API being called has strict rate limits. In parallel mode, iterations run concurrently up to max_concurrency — use this for independent items like batch notification sends.

In development stage, loops execute against live data with the exact iteration count in the input. In demo and live stages, the same behavior applies but the rate-limit modifier is especially important to prevent loop elements from overwhelming downstream services.

Example Project Spec

# Parallel batch notification sender with error tolerance
elements:
  - element_type: loop
    slug: notify-users
    spec:
      mode: parallel
      max_concurrency: 10
      max_iterations: 5000
      timeout_ms: 120000
      error_handling:
        on_error: continue
        max_failures: 50
      result:
        collect: true
        filter: "item.status == 'sent'"

Common Patterns

Batch Processing with Parallel Execution

Process a list of records in parallel, collecting only successful results:

POST /api/{circle}/{project}/

{
  "element_type": "loop",
  "slug": "batch-processor",
  "spec": {
    "mode": "parallel",
    "max_concurrency": 20,
    "error_handling": {"on_error": "continue"},
    "result": {
      "collect": true,
      "filter": "item.success == true"
    }
  }
}

Invoke with a list of payloads:

POST /api/{circle}/{project}/batch-processor/ops/invoke

{
  "items": [
    {"record_id": "r-1", "data": {...}},
    {"record_id": "r-2", "data": {...}}
  ]
}

Range-Based Pagination

Iterate over page numbers to fetch paginated API data:

POST /api/{circle}/{project}/

{
  "element_type": "loop",
  "slug": "paginated-fetch",
  "spec": {
    "mode": "sequential",
    "items": {"start": 1, "end": 10, "step": 1},
    "body_ref": "fetch-page",
    "break_condition": "iteration.result.has_more == false"
  }
}

Invoke without any items — the range provides the iteration values:

POST /api/{circle}/{project}/paginated-fetch/ops/invoke

{}

Applying Modifiers

ModifierUse case
rate-limitCap the total invocations per second across all parallel iterations
requirementsRequire that specific variable resources are available before the loop starts

Common Mistakes

Forgetting max_iterations for while-style loops. The default max_iterations is 1000. For loops that use break_condition to exit early (effectively a while loop), set max_iterations to a value large enough for your worst-case scenario but low enough to prevent runaway execution.

Using parallel mode on ordered operations. Parallel mode does not guarantee iteration order. If each iteration depends on the result of the previous one (e.g., paginating with cursor-based APIs), use sequential mode.

Setting on_error: continue without max_failures. If every iteration fails in continue mode, the loop runs to completion but the output is all failures. Set max_failures to a sensible threshold (e.g., 10% of expected items) so the loop aborts if the failure rate is unacceptably high.

Omitting items field. items is a required field. Invoking a loop without providing items in the request body and without a static items expression in spec results in a validation error.

Relationships

  • Attaches to: rate-limit
  • Uses: variable

Capabilities

  • iteration: For-each and range loops
  • parallel: Parallel iteration with concurrency control
  • early-exit: Break condition support

Properties

PropertyTypeDefaultDescription
body_refstringReference to the element to execute in each iteration
itemsobjectItems to iterate over
modestring"sequential"Execution mode
max_concurrencyinteger10Max parallel iterations (only applies in parallel mode)
max_iterationsinteger1000Safety limit — loop stops after this many iterations regardless of items
timeout_msinteger300000Overall loop timeout in milliseconds (all iterations combined)
break_conditionstringCEL expression for early exit
continue_conditionstringCEL expression to skip iteration
error_handlingobjectError handling for individual iteration failures
resultobjectResult accumulation settings

Operations

activity

Get /ops/activity | Auth: Read

Get activity events for this element

Scope depends on element capabilities: individual elements query by element_id, project-form elements with activity-scope-members include member activities, circle-level elements with activity-scope-all query the entire circle. Gracefully returns empty list if activities table is missing (old circles).

attachments

Get /ops/attachments | Auth: Read

List all modifiers and resources attached to this element

Returns both modifiers (policy enforcement) and resources (data injection) with is_modifier flag to distinguish. Items in the generated MODIFIER_TYPES list are modifiers; everything else is a resource. Includes cascade_policy and version pin info.

batch_stats

Get /ops/batch_stats | Auth: Read

Get per-element statistics for all children of this element

Returns per-child stats plus an aggregate. Most meaningful on compound or manifest form elements (repositories, circles, projects); atoms have no children so the result is an empty children array with a zeroed aggregate. Uses efficient GROUP BY SQL. Weighted averages for eval scores.

break

Post /ops/break | Auth: Execute

Break out of the loop early

Stop a running loop early. Requires loop_run_id. Sets loop status to cancelled with break_reason. Returns completed_count and remaining_count.

compose

Post /ops/compose | Auth: Execute

Batch add and remove modifiers on this element in a single call

Declarative composition: add modifiers by ref path (slug or path@version) and remove by attachment ID, all in one atomic call on the target element. Each ‘add’ entry resolves the source element, validates topology, attaches with optional priority and cascade policy. Each ‘remove’ entry deletes the attachment row. Returns a summary of what was added and removed. Example: compose({ add: [{ref: “my-prompt”}, {ref: “rate-limit/api@v2”, priority: 50}], remove: [{attachment_id: “uuid”}] })

context

Get /ops/context | Auth: Read

Get connected elements (graph traversal)

Graph traversal showing all connected elements with their relationship type (contains, contained_by, references, referenced_by, attaches, etc.). Use ?depth=N to control traversal depth (default 1) and ?types=actor,data to filter by element types.

continue_loop

Post /ops/continue | Auth: Execute

Skip current iteration and continue to next

Skip the current iteration in a running loop. Requires loop_run_id. Returns the next_index that will be processed.

create

Post /ops/create | Auth: Write

Create child element

POST to the parent path — element_type goes in the request body, NOT the URL. Both element_type and slug are required and must be non-empty. Name is derived from slug if omitted. Writes to both Git and PostgreSQL. All elements are stored flat under the circle — no intermediate library wrapper rows.

delete

Delete /ops/delete | Auth: Admin

Delete element (soft delete)

Soft delete — sets state to ‘deleted’ but retains the record. Cannot delete elements that have children (has_no_bond precondition) or active runs. Requires admin auth and confirmation.

disable

Post /ops/disable | Auth: Admin

Disable element (hides and prevents use)

Idempotent — safe to call on already-disabled elements. Optionally pass a reason string. Disabled elements cannot be invoked or executed. Inverse of enable.

enable

Post /ops/enable | Auth: Admin

Enable element (makes usable and visible)

Idempotent — safe to call on already-enabled elements. Transitions element to ready/enabled state. Cannot enable deleted elements. Inverse of disable.

execute

Post /ops/execute | Auth: Execute

Execute the loop over a collection of items

Iterate over items array, calling body_ref element for each. Requires items:[] (array). Set concurrency (default: 1) and continue_on_error (default: false). Returns loop_run_id and per-item results with status, duration_ms. Fails fast by default — set continue_on_error: true to process all items. Max items limited by spec.max_iterations (default: 1000).

export_bundle

Get /ops/export/bundle | Auth: Read

Export element as downloadable git bundle

On non-root-namespace elements, returns a binary git bundle. On root-namespace (circle) elements, dispatch hands off to the circle’s own export_bundle op, which returns a multi-element JSON envelope with one base64 bundle per child element — this is intentional, not an error.

get

Get /ops/get | Auth: Read

Get element details

Element is already resolved by the routing layer — this returns the cached element, not a fresh DB query. Use the path /api/{circle}/{slug} to address elements.

import_bundle

Post /ops/import/bundle | Auth: Write

Import git bundle into element

Accepts a base64-encoded git bundle in the JSON bundle_base64 field. Use overwrite=true to replace existing elements with same slug (default skips duplicates). Imported elements get new UUIDs. Returns counts of imported/skipped elements and any errors.

intention

Get /ops/intention | Auth: Read

Get element intention with full inheritance chain

Returns three levels: direct (this element’s intention), inherited (from category and root), and resolved (final merged intention). Useful for understanding an element’s purpose in context of its hierarchy.

loop_status

Get /ops/status/{loop_run_id} | Auth: Read

Get detailed loop execution status

Get progress of a loop execution. Requires loop_run_id. Returns status, total_items, completed_count, failed_count, current_index, and timestamps.

promote

Post /ops/promote | Auth: Admin

Promote element configuration to a target environment

Only for manifest-form elements (projects). Environments advance: dev → demo → live. dev→demo requires member+ role, demo→live requires admin. Freezes member versions at promotion time (creates snapshot). Persists environment config to spec.environments.

readme

Get /ops/readme | Auth: Read

Get element README.md content

Reads README.md from the element’s git repository. Returns empty content (not an error) if no README exists. Always returns markdown format.

readme_update

Post /ops/readme_update | Auth: Write

Update element README.md content

Creates or overwrites README.md in the element’s git repo. Commits to the draft branch. Content must be provided as a markdown string.

remove-modifier

Post /ops/remove-modifier | Auth: Execute

Remove an attached modifier from this element by attachment ID

Removes a modifier/resource attachment by its row ID. The ID comes from the attachments or context API. This is the reverse of attach — called on the target element, not the source.

restore

Post /ops/restore | Auth: Admin

Restore element to a specific version

Automatically snapshots the current state before restoring (creates a ‘Before restore to vN’ version entry). Writes restored spec to git as .triform/spec.yaml. Git failures warn but don’t fail the operation — DB state is authoritative. Cannot restore deleted elements.

schema

Get /ops/schema | Auth: Read

Get element input/output schema (MCP tools/list compatible)

Returns type-level port schemas from the TypeRegistry — not instance-specific overrides. Includes direction (input/output), required flag, and JSON schema per port. Useful for understanding what data an element accepts and produces.

source

Get /ops/source | Auth: Read

Get any file’s content from the element’s git repository

Reads an arbitrary file from the element’s CAS-backed git tree by its relative path. Same store as readme, just generalized. Path safety: rejects .. traversal, leading /, and null bytes. Use this to view main.py for action elements, asset files for SPAs, etc. Returns empty content (not an error) if the file doesn’t exist.

source_branches

Get /ops/source/branches | Auth: Read

List Source branches for this element

Returns the standard draft/demo/live Source branches, their current commits, and promotion relationships. Use GET /api/{element_path}/ops/source/branches.

source_promote

Post /ops/source/promote | Auth: Write

Promote Source branch forward

Promotes draft to demo or demo to live through the generated element op path. Direct Git pushes to demo/live are blocked by Source policy.

source_repair

Post /ops/source/repair | Auth: Write

Inspect or repair the element Source index

Runs Source repair through the element operation path. Defaults to dry_run=true; set dry_run=false only after reviewing a dry-run report.

source_status

Get /ops/source/status | Auth: Read

Get Source control status for this element

Returns the branch-aware clone URL, checkout commands, current draft commit, child source-link count, portable export summary, Source health, warnings, and auth hints for the addressed element. Use the element-first path: GET /api/{element_path}/ops/source/status.

source_validate

Post /ops/source/validate | Auth: Read

Validate Source branch contents

Validates a Source branch before accepting local Git workflow changes or promotion. Defaults to branch=draft and rejects runtime data, generated output, secret material, and unreadable CAS refs.

stats

Get /ops/stats | Auth: Read

Get aggregate statistics for this element

Health status is computed: error if errors_per_day > 5 or success_rate < 0.8, warning if errors_per_day > 0 or success_rate < 0.95. Firing alerts escalate health to error/warning. Default period is ‘day’. Returns runs_per_day, success_rate, avg_duration_ms, and more.

tree

Get /ops/tree | Auth: Read

Get the element’s position in the graph — ancestors, children, references, and subtree statistics

Uses per-circle ElementGraph cache for O(1) lookups. Returns ancestors (containment chain), children (direct), members (references), referenced_by (reverse refs), attachments, and subtree stats. Default depth is 3, max is 10. Pass ?include_metadata=true for name/state on each node.

update

Patch /ops/update | Auth: Write

Update element

Partial update — send only the fields you want to change. spec, name, and intention are all independently optional. spec MUST be a JSON object when present; deep-merged into the existing spec by default. Empty {"spec":{}} preserves existing spec content but still records a new version (no-op for content, not for version state). To clear/replace the entire spec wholesale send {"spec":{...},"deep":false}. List-typed spec fields use replace semantics (the patch list replaces the existing list, no array merging). Coordinates Git + DB writes. Slug cannot be changed after creation.

update_meta

Patch /ops/update_meta | Auth: Write

Update element metadata (lightweight merge — does NOT bump version or snapshot spec)

Shallow JSONB merge into element.meta. Top-level keys in the provided value replace existing meta values; other keys are preserved. Used for UI metadata like canvas positions, panel state, viewer preferences. Wire-shape op_name is update_meta (distinct from update) so SSE subscribers + the cache auto-invalidator can distinguish lightweight metadata changes from spec edits without inspecting the payload. The MutatingElementStore wrapper stamps this op_name on the lifecycle event emitted by update_element_meta storage calls.

version

Get /ops/version | Auth: Read

Get current version or full history

Returns current version by default. Pass ?history=true for full version history (up to ?limit=N, default 50). Versions are backed by the element_versions table. Every spec update creates a new version entry.

Error Codes

CodeClassRetryableDescription
LOOP_MAX_ITERATIONSlimitnoExceeded maximum iteration limit
LOOP_ITERATION_FAILEDinternalnoAn iteration failed

Lifecycle / runtime

Defined for this element

Before invoke

  • validate_input
  • check_rate_limit

After invoke

  • record_metrics
  • emit_traces

On error

  • log_error
  • record_error_metric

Observability

Defined for this element

Metrics

  • loop_count
  • iteration_count
  • duration_ms
  • error_rate

Events

  • loop.completed
  • loop.failed

Pricing / cost

Platform default

Operation costs

  • create: free
  • update: free
  • delete: free
  • get: free
  • list: free
  • invoke: 10000 micro-AU
  • tool_use: free