Download all docs
actions

Rust

Your own compiled Rust, run inside a sandboxed Firecracker microVM — the binary is built once with Cargo, cached in object storage, and reloaded on every call, giving rust-fn the lowest cold-start latency and highest throughput of any function type on Triform.

Working with it

Opening a Rust launches a code runner — its dedicated working surface.

How it appears

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

Rs
type

Rust

Execute compiled Rust code in a sandboxed environment

actionsatomdefinition

When to use / not

When to use

  • A hot path where latency and throughput matter — rust-fn carries the lowest cold-start and highest throughput of any function type, since each invoke reloads a cached compiled binary instead of a runtime.
  • Compute-heavy work you want statically typed and compiled — your handler takes a serde_json::Value and returns a Value or a String, with Cargo dependencies declared in spec.source.requirements.
  • Logic you already maintain as a Cargo project — point spec.source at a git repo and ref instead of pasting inline code.
  • A step wired between other elements — sit a rust-fn between a trigger and a database to transform the resolved payload as it flows through.

When not to use

  • Quick scripting or glue where edit-and-go beats raw speed — python or javascript skip the cold Cargo compile (~7.6s on first invoke) entirely.
  • Reaching an external service with no transform — an http element makes the request directly without a function in between.
  • A step that must pause for a human decision — that is what hitl is for, not a compiled function.

Topology

Created from the library and placed inside an app or circle. It is a top-level building block you compose with other elements.

Properties

sourceobjectrequired
Source code configuration
handlerstring
Entry point function. Default: handler() -> main()
timeout_msinteger
Maximum execution time in milliseconds

Capabilities

Defined for this element
  • Compute
  • Observe
  • Storage

Operations

  • activityGET
  • attachPOST
  • attachmentsGET
  • batch_statsGET
  • buildPOST
  • composePOST
  • contextGET
  • createPOST
  • deleteDELETE
  • detachPOST
  • diagnosticsGET
  • disablePOST
  • enablePOST
  • export_bundleGET
  • getGET
  • get_attached_modifiersGET
  • import_bundlePOST
  • intentionGET
  • invokePOST
  • list_attachmentsGET
  • logsGET
  • promotePOST
  • readmeGET
  • readme_updatePOST
  • remove-modifierPOST
  • restorePOST
  • run_cancelPOST
  • run_getGET
  • runsGET
  • schemaGET
  • sourceGET
  • source_branchesGET
  • source_promotePOST
  • source_repairPOST
  • source_statusGET
  • source_validatePOST
  • statsGET
  • treeGET
  • updatePATCH
  • update_metaPATCH
  • validatePOST
  • versionGET
  • warmPOST

Ports

Inputs

  • inputrequest
  • outputrequest
  • errorevent

Composition

Errors / when it fails

source.code is required when source.type is inline
Fails unless: source.code != null && source.code != ''
source.git_url is required when source.type is git
Fails unless: source.git_url != null && source.git_url != ''
handler must be a valid snake_case Rust function name
Fails unless: handler =~ '^[a-z_][a-z0-9_]*$'

Validation rules

  • memory_mb over 1024MB — consider whether your function truly needs this much memory
  • timeout_ms over 5 minutes — long-running functions may be better suited to an agent element
  • Pinning to 'main' branch means code changes automatically — consider pinning to a commit SHA for stable deployments

Rust (rust-fn)

Category: actions | Form: | Symbol: Rs

Execute compiled Rust code in a sandboxed environment

Compiles and runs Rust code in a sandboxed Firecracker VM. Code is compiled ahead of time and the binary is cached. Rust functions have the lowest cold-start latency and highest performance. Put your code in spec.source.code or point to a git repository. Your code must define a handler function. Supports Cargo dependencies via spec.source.requirements.

Guide

Execute compiled Rust code in a sandboxed Firecracker VM.

Overview

The rust-fn element compiles your Rust source code using Cargo and runs the resulting binary inside a Firecracker microVM. The compiled binary is cached in object storage — subsequent invocations skip compilation and start immediately. Rust functions offer the lowest latency and highest throughput of any function type on Triform.

Input Contract

Your handler receives a serde_json::Value containing the caller’s payload. The platform automatically unwraps common envelope patterns (payload, data, input keys) and strips internal metadata, so your handler always sees the clean user data.

Direct invoke — the JSON body is passed through:

POST /api/{circle}/my-greeter/ops/invoke
{"name": "Alice", "count": 3}
pub fn handler(input: Value) -> Value {
    // input = {"name": "Alice", "count": 3}
    let name = input["name"].as_str().unwrap_or("World");
    serde_json::json!({"greeting": format!("Hello, {}!", name)})
}

Envelope invoke — the platform unwraps payload/data/input keys automatically:

POST /api/{circle}/my-greeter/ops/invoke
{"payload": {"name": "Alice"}}
// handler still receives {"name": "Alice"} — envelope is stripped

Wired invoke (from automation steps or other elements) — the orchestrator shapes inputs based on port topology. Your handler receives the resolved payload, not raw wire data.

Quick Start

element_type: rust-fn
slug: my-greeter

spec:
  source:
    type: inline
    code: |
      use serde_json::Value;

      pub fn handler(input: Value) -> Value {
          let name = input.get("name")
              .and_then(|v| v.as_str())
              .unwrap_or("World");
          serde_json::json!({
              "message": format!("Hello, {}!", name)
          })
      }
  handler: handler

Source Configuration

Inline Code

Set spec.source.type: inline and provide your code in spec.source.code. The handler function signature must accept a serde_json::Value and return a serde_json::Value.

Cargo Dependencies

Add crate dependencies in spec.source.requirements using standard Cargo.toml syntax:

spec:
  source:
    type: inline
    code: |
      use reqwest::Client;
      use serde_json::Value;

      pub async fn handler(input: Value) -> Value {
          // ...
      }
    requirements: |
      reqwest = { version = "0.12", features = ["json"] }
      tokio = { version = "1", features = ["full"] }

Git Repository

Point to a Git repository containing your Cargo project:

spec:
  source:
    type: git
    git_url: "https://github.com/example/my-fn.git"
    git_ref: "v1.0.0"
  handler: handler

Handler Signature

Your handler must be a public function named according to spec.handler (default: handler). Supported signatures:

// Synchronous
pub fn handler(input: serde_json::Value) -> serde_json::Value { ... }

// Synchronous with error
pub fn handler(input: serde_json::Value) -> Result<serde_json::Value, Box<dyn std::error::Error>> { ... }

// Async
pub async fn handler(input: serde_json::Value) -> serde_json::Value { ... }

Resource Limits

FieldDefaultRange
timeout_ms30000100 – 900000
memory_mb12864 – 4096

Operations

OperationDescription
invokeCall the handler with input data
buildCompile ahead of time (pre-warm cache)
validateRun cargo check without building
runsList recent invocation history
run_getFetch details for a specific run
logsFetch stdout/stderr from runs

Wiring

Connect this function to other elements via wires:

wires:
  - source: my-webhook
    target: my-greeter
  - source: my-greeter
    target: my-database

Error Codes

CodeDescription
RUST_FN_COMPILATION_FAILEDCargo build error
RUST_FN_EXECUTION_FAILEDRuntime panic in the handler
RUST_FN_TIMEOUTExceeded timeout_ms
RUST_FN_MEMORY_EXCEEDEDExceeded memory_mb
RUST_FN_INVALID_OUTPUTHandler returned non-serializable value

Relationships

  • Attaches to: variable, secret, rate-limit, validation, alert, auth-policy
  • Uses: sql, document, files, vector, git

Capabilities

  • compiled: Code is compiled ahead-of-time; binary is cached between invocations
  • cargo-dependencies: Supports Cargo.toml dependencies via spec.source.requirements
  • sandboxed: Runs inside a Firecracker microVM with strict resource limits
  • binary-cache: Compiled binary is cached and reused on subsequent invocations

Properties

PropertyTypeDefaultDescription
sourceobjectSource code configuration
handlerstring"handler"Entry point function. Default: handler() -> main()
envobjectEnvironment variables injected at runtime
timeout_msinteger30000Maximum execution time in milliseconds
memory_mbinteger128Memory limit for the sandbox VM in megabytes
data_sourcesarrayData elements this function can access

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).

attach

Post /ops/attach | Auth: Read

Attach this actor to a target element

Call this ON the modifier/resource element, passing target_id of the actor. The target’s contract.yaml must declare the modifier kind in attaches: or uses:. Priority controls evaluation order for modifiers (lower = first).

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.

build

Post /ops/build | Auth: Write

Compile the Rust function ahead of time

Trigger a Cargo build without invoking the handler. Useful to pre-warm the binary cache or validate that compilation succeeds before deployment. Returns build status and any compiler diagnostics.

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.

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.

detach

Post /ops/detach | Auth: Read

Detach this actor from a target element

diagnostics

Get /ops/diagnostics | Auth: Read

Check isolation service connectivity and health

Returns the status of the isolation executor that this element depends on for code execution. Use this to distinguish between user code errors and infrastructure issues when invoke returns 500. Returns isolation_reachable (bool), worker_available (bool), and last_error if any.

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.

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.

get_attached_modifiers

Get /ops/attached | Auth: Read

Get elements that are attached to this action

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.

invoke

Post /ops/invoke | Auth: Execute

Invoke the Rust function with input data

Call the compiled Rust handler with a JSON payload. The function is compiled on first invoke (or after source changes) and the binary is cached. Returns the handler’s return value as JSON. Input contract: your handler receives a serde_json::Value containing the caller’s data directly. The platform auto-unwraps envelope keys (payload, data, input) so you always get the clean payload. Example: fn handler(input: Value) -> Value { let name = input[“name”].as_str().unwrap_or(“World”); json!({“hello”: name}) }. Both fn handler(input: Value) -> Value and fn handler(input: Value) -> String are supported.

list_attachments

Get /ops/targets | Auth: Read

List all elements this action is attached to

Returns all target elements where this action is currently attached. Shows target_id, target_type, priority, and cascade_policy.

logs

Get /ops/logs | Auth: Read

Stream or fetch logs from recent function invocations

Fetch stdout/stderr logs from function runs. Filter by run_id to see logs from a specific invocation. Supports tail (last N lines) or since (timestamp). Returns log lines with 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.

run_cancel

Post /ops/runs/{run_id}/cancel | Auth: Execute

Cancel a running execution

Only works on runs with status pending or running. Already-completed or failed runs cannot be cancelled. The run transitions to cancelled state and triggers run.cancelled event.

run_get

Get /ops/runs/{run_id} | Auth: Read

Get details for a specific invocation run

Fetch full details for a run including input, output, error (if any), and execution metadata. run_id is required.

runs

Get /ops/runs | Auth: Read

List recent invocation runs

Returns recent runs for this function with status, duration, and timestamps. Supports pagination via cursor. Each run includes run_id you can use with run_get to fetch full output.

schema

Get /ops/schema | Auth: Read

Get input/output port schemas (MCP tools/list compatible)

Call this before invoking an actor to discover its expected input/output format. Returns MCP-compatible tool definitions — useful for building dynamic tool UIs or A2A integration.

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.

validate

Post /ops/validate | Auth: Read

Validate Rust source code and Cargo dependencies

Run cargo check against the source code without building a binary. Faster than a full build — catches compilation errors and type mismatches. Returns valid (boolean), errors, and warnings.

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.

warm

Post /ops/warm | Auth: Read

Pre-compile the Rust function without executing it

Trigger ahead-of-time compilation to eliminate first-invocation latency (~7.6s cold compile). Call this on dashboard open or element focus to pre-heat the binary cache. Returns immediately if the binary is already cached. Unlike build, this uses read auth so dashboards and automations can call it without elevated permissions.

Error Codes

CodeClassRetryableDescription
RUST_FN_COMPILATION_FAILEDvalidationnoRust compilation error — check your source code and Cargo dependencies
RUST_FN_EXECUTION_FAILEDinternalyesRuntime panic or unhandled error in the handler function
RUST_FN_TIMEOUTtimeoutyesFunction execution exceeded timeout_ms limit
RUST_FN_MEMORY_EXCEEDEDinternalnoFunction exceeded its memory_mb allocation
RUST_FN_INVALID_OUTPUTvalidationnoHandler returned a value that could not be serialized to JSON

Lifecycle / runtime

Defined for this element

Before invoke

  • validate_source
  • resolve_data_sources
  • check_rate_limit

After invoke

  • record_metrics
  • emit_traces

On error

  • log_error
  • record_error_metric

Observability

Defined for this element

Metrics

  • rust_fn_invocation_count
  • rust_fn_duration_ms
  • rust_fn_error_rate
  • rust_fn_build_duration_ms
  • rust_fn_cache_hit_rate

Events

  • rust_fn.invoked
  • rust_fn.completed
  • rust_fn.failed
  • rust_fn.build_completed

Pricing / cost

Inherited from actions

Operation costs

  • invoke: 10000 micro-AU