Golem retry policies ts

From golemcloud/golem · View interactive version

Golem retry policies ts is an AI agent skill from the GitHub repository golemcloud/golem. Configuring semantic retry policies for a TypeScript Golem agent. Use when the user asks about retry policies, retry strategies, exponential backoff, error handling retries, transient error recovery, retry predicates, withRetryPolicy, NamedPolicy, Policy composition, jitter, countBox, timeBox, andTh

How to use this skill

Skill file

Configuring Semantic Retry Policies (TypeScript)

Golem provides a composable, per-environment retry policy system. Policies are evaluated against error context properties and can be defined in the application manifest, managed via CLI, or created/overridden at runtime from agent code using the SDK.

Do not predicate on is-idempotent; the host no longer supplies that property. The explicit

golem:api/host.trap function raises a deterministic trap and is never retried, even by a catch-all policy. Host retry

policies repair eligible individual calls, not completed effects or whole saga attempts.

A trap is permanent. Return an error for a transient condition and use a retry schedule.

Application-level errors need application-level handling; returning an error does not automatically

activate a host retry policy.

1. Define Retry Policies in the Application Manifest

Add retry policy definitions under retryPolicyDefaults in golem.yaml, scoped per environment:

retryPolicyDefaults:
  prod:
    http-transient:
      priority: 10
      predicate:
        and:
          - propEq: { property: "error-type", value: "transient" }
          - propEq: { property: "uri-scheme", value: "https" }
      policy:
        countBox:
          maxRetries: 5
          inner:
            jitter:
              factor: 0.15
              inner:
                clamp:
                  minDelay: "100ms"
                  maxDelay: "5s"
                  inner:
                    exponential:
                      baseDelay: "200ms"
                      factor: 2.0

    catch-all:
      priority: 0
      predicate: true
      policy:
        countBox:
          maxRetries: 3
          inner:
            exponential:
              baseDelay: "100ms"
              factor: 3.0

Policy Evaluation Order

When an error occurs, policies are evaluated in descending priority order. The first matching predicate's policy is applied. If no user-defined policy matches, the built-in default policy (3 total attempts: the initial attempt and up to 2 retries, exponential backoff, clamped to [100ms, 1s], 15% jitter) is used.

Base Policies

| Policy | Description |

|--------|-------------|

| periodic | Fixed delay between each attempt |

| exponential | baseDelay × factor^attempt — exponentially growing delays |

| fibonacci | Delays follow the Fibonacci sequence starting from first and second |

| immediate | Retry immediately (zero delay) |

| never | Never retry — give up on first failure |

Combinators

| Combinator | Description |

|------------|-------------|

| countBox | Limits the total number of retry attempts |

| timeBox | Limits retries to a wall-clock duration |

| clamp | Clamps computed delay to a [minDelay, maxDelay] range |

| addDelay | Adds a constant offset on top of the computed delay |

| jitter | Adds positive jitter, producing a delay in [delay, delay + factor × delay], to avoid thundering herds |

| filteredOn | Apply the inner policy only when a predicate matches; otherwise give up |

| andThen | Run the first policy until it gives up, then switch to the second |

| union | Retry if either sub-policy wants to; pick the shorter delay |

| intersect | Retry only while both sub-policies want to; pick the longer delay |

Predicates

Predicates are boolean expressions evaluated against error context properties. Compose with and, or, not:

Available Properties

Every retry decision happens in a specific context (an outgoing HTTP request, an HTTP

response, a worker-to-worker RPC call, a trap from inside the guest, etc.). Each context only

populates a subset of the property vocabulary below — a policy keyed on a property that is **not

present in the current context is silently skipped** for that decision (it cannot apply there by

definition).

Common to every context:

dns://..., wasm://<function> for traps, golem://api, …)

Context-specific properties:

| Property | Populated in |

|-------------------------|-------------------------------------------------------|

| status-code | outgoing HTTP response only |

| error-type | outgoing HTTP response only |

| function | worker-to-worker RPC call |

| target-component-id | worker-to-worker RPC call |

| target-agent-type | worker-to-worker RPC call |

| db-type | RDBMS operations (e.g. postgres, mysql) |

| trap-type | guest WASM trap (transient-error, unknown, …) |

Practical consequence. A status-code-keyed policy (predicate: status-code in [...]) only

fires for HTTP responses. The trap path does not see status-code and silently skips that

policy — it does not error out. Likewise, a trap-type-keyed policy only fires from the

trap path. Design one policy per context (or use or/and to make a policy explicitly match

multiple contexts) rather than expecting a single policy to apply everywhere.

`error-type` values

Status-code retries (opt-in)

Outgoing HTTP responses (including those returned by fetch()) now flow through the retry-policy

machinery: when the response arrives, its status-code is exposed to predicates. **A policy is

only considered for status-code retries if its predicate (or the predicate inside a nested

FilteredOn) explicitly references the status-code property.** Catch-all policies — including

the synthesized default and any user-defined "matches all" policy — are intentionally excluded so

status-based retries remain strictly opt-in.

When a matching policy decides to retry, the rejected response is dropped, the request body is

reconstructed from the oplog, and the request is re-sent without a user-land throw.

Eligibility rules (mirror inline transport retry):

Example status-code policy:

http-5xx-retry:
  priority: 20
  predicate:
    and:
      - propIn: { property: "status-code", values: [500, 502, 503, 504] }
      - propEq: { property: "uri-scheme", value: "https" }
  policy:
    countBox:
      maxRetries: 3
      inner:
        exponential:
          baseDelay: "200ms"
          factor: 2.0

fetch() interaction: fetch() resolves with a Response for HTTP 4xx/5xx

statuses. If a status-code-keyed retry policy matches, the host transparently re-sends the

request and the resolved Response will be the result of the last attempt. For a retry

decision based on a parsed body, use explicit guest control flow or an SDK saga. New attempts

append new calls; throwing after a response does not retry that completed request.

2. SDK: Build and Apply Retry Policies at Runtime

Use @golemcloud/golem-ts-sdk to construct and apply retry policies from agent code:

import {
  Policy, Predicate, NamedPolicy, Props, Duration,
  withRetryPolicy,
} from '@golemcloud/golem-ts-sdk';

const policy = NamedPolicy.named(
  'http-transient',
  Policy.exponential(Duration.milliseconds(200), 2.0)
    .clamp(Duration.milliseconds(100), Duration.seconds(5))
    .withJitter(0.15)
    .onlyWhen(Predicate.eq(Props.errorType, 'transient'))
    .maxRetries(5),
)
  .priority(10)
  .appliesWhen(Predicate.eq(Props.uriScheme, 'https'));

Scoped Usage with `withRetryPolicy`

Apply a policy for a block of code. The block runs inside a retry policy scope: the policy

overrides the agent-wide policy with the same name for host calls until the block exits or its

Promise settles. The scope changes no agent-wide policy and records no oplog entry. JavaScript

code of one agent runs on one component-model task, so other async work of the same invocation

that runs while the scope is open also sees the policy:

withRetryPolicy(policy, () => {
  // HTTP calls in this block use the custom retry policy
  makeHttpRequest();
});

Host policies retry eligible individual calls at their own Start. They do not rerun a guest

callback or erase earlier results. Use the saga helpers for reverse-order compensation and a

separate guest-code attempt.

Policy Builder Methods

Build policies fluently from base policies:

// Exponential backoff clamped with jitter and max retries
Policy.exponential(Duration.milliseconds(200), 2.0)
  .clamp(Duration.milliseconds(100), Duration.seconds(5))
  .withJitter(0.15)
  .maxRetries(5)

// Periodic with time limit
Policy.periodic(Duration.seconds(1))
  .timeBox(Duration.seconds(60))

// Immediate retries then fall back to exponential
Policy.immediate()
  .maxRetries(3)
  .andThen(
    Policy.exponential(Duration.seconds(1), 2.0)
      .maxRetries(5)
  )

// Never retry (fail immediately)
Policy.never()

Predicate Builder Methods

// Match transient host-level failures
Predicate.eq(Props.errorType, 'transient')

// Match a property value
Predicate.eq(Props.uriScheme, 'https')

// Combine predicates
Predicate.and([
  Predicate.eq(Props.errorType, 'transient'),
  Predicate.eq(Props.uriScheme, 'https'),
])

3. Querying Retry Policies at Runtime

Use the query API to inspect active policies from agent code:

import { getRetryPolicies, getRetryPolicyByName } from '@golemcloud/golem-ts-sdk';

// List all active policies
const policies = getRetryPolicies();
for (const p of policies) {
  console.log(`Policy '${p.name}' priority=${p.priority}`);
}

// Get a specific policy by name
const policy = getRetryPolicyByName('http-transient');
if (policy) {
  console.log(`Found policy with priority ${policy.priority}`);
}

The returned NamedRetryPolicy has fields: name (string), priority (number), predicate (RetryPredicate), policy (RetryPolicy).

4. Live-Editing Policies via CLI

Retry policies can be managed at runtime without redeployment:

# Create a new policy
golem retry-policy create http-transient \
  --priority 10 \
  --predicate '{ "and": [{ "propEq": { "property": "error-type", "value": "transient" } }, { "propEq": { "property": "uri-scheme", "value": "https" } }] }' \
  --policy '{ "countBox": { "maxRetries": 5, "inner": { "exponential": { "baseDelay": "200ms", "factor": 2.0 } } } }'

# List all policies in the current environment
golem retry-policy list

# Get a specific policy by name
golem retry-policy get http-transient

# Update an existing policy
golem retry-policy update http-transient --priority 15

# Delete a policy
golem retry-policy delete http-transient

5. Default Retry Policy

When no user-defined retry policies are set, Golem activates a default catch-all:

Key Constraints

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.