Wrocław, DRUG
Temporal, CEL, and the log that never calls itself event sourcing
Robert Pankowecki
job run_agent_task(task):
workspace = clone_repo(task.repo) # 3 minutes
image = build_image(workspace) # 30 minutes
result = run_agent(image, task.prompt) # 2 hours
run_tests(result) # 20 minutes
open_pull_request(result) # 2 seconds, flaky
The last call returns a 502. Retry the job: 3 hours, gone.
Too long for a request. Too flaky to run once. Too expensive to run twice.
From a Rust system at work that runs AI agent workflows. All code here is pseudocode.
job build(task):
task.image = build_image(task.workspace)
task.status = "built"
enqueue run_agent(task)
job run_tests(task):
for shard in task.shards:
enqueue run_shard(task, shard)
task.status = "testing"
job run_shard(task, shard):
run_tests_for(task, shard)
task.shards_done += 1
if task.shards_done == task.shards.size: # two finish at once?
enqueue open_pull_request(task)
Nowhere. It is smeared across six files, a column and a cron.
Temporal isn't magic here either: its UI shows what ran, not what comes next. To show your users, you write queries.
| Idea | Examples |
|---|---|
| Queues with batches | Sidekiq Pro, GoodJob, Solid Queue |
| Resumable steps in a job | ActiveJob::Continuable, chrono_forge |
| Process managers | Rails Event Store |
| Durable execution engines | Restate, DBOS, Inngest, Hatchet |
I haven't researched or verified these. Just pointers.
Act 2
class AgentWorkflow < Workflow
def execute(task)
workspace = activity :clone_repo, task.repo, timeout: 5.minutes
image = activity :build_image, workspace, timeout: 1.hour
result = activity :run_agent, image, timeout: 3.hours
pr = activity :open_pull_request, result
sleep 3.days # really
activity :ping_reviewers, pr unless activity(:merged?, pr)
end
end
A worker can die on any line. This still finishes.
Decides what happens next
Touches the world
Activities are how you hook in. Everything real is an activity.
Temporal never runs your code. Your workers poll it.
dir = activity :clone_repo img = activity :build_image res = activity :run_agent
dir = activity :clone_repo img = activity :build_image res = activity :run_agent
Same code, same inputs, same decisions. Nothing was cloned or built again.
“The system functions via event sourcing: an append-only history of events is stored for each workflow execution, and all required workflow state can be recreated at any time by replaying this history.”
temporalio/temporal, docs/architecture/README.md
| Event sourcing | Temporal |
|---|---|
| Stream | Workflow execution history |
| Command → Event | Command → Event (literally) |
| Rebuild the aggregate | Replay |
| Snapshot | Sticky worker cache |
| Read model | Query |
| Process manager | Workflow |
One big difference: these events are about execution, not your domain.
# Process manager
class AgentProcess
subscribes_to ImageBuilt, AgentFinished
def apply(event)
case event
when ImageBuilt then @image = event.image
when AgentFinished then @result = event.result
end
end
def act
return open_pr(@result) if @result
run_agent(@image) if @image
end
end
# Workflow
class AgentWorkflow < Workflow
def execute(task)
image = activity :build_image, task
result = activity :run_agent, image
activity :open_pr, result
end
end
# apply/act is still there.
# The language runtime wrote it:
# the stack frame IS the state.
add :: Int -> Int -> Intsave :: Row -> IO ()
class BadWorkflow < Workflow
def execute
Time.now
end
end
Cannot access Time now from inside a workflow, reason: Invalid Time.now call.
Cannot access File pathI haven't used Temporal in Ruby. This is from the SDK docs and a small test.
Act 3
queue = images.dup
lanes = 3.times.map do
async do
while (image = queue.shift)
activity :build_docker_image, image
end
end
end
all_of(lanes).wait
An array. No Redis, no semaphore, no lock.
The 3 is now part of your history. Change it to 5 and old runs stop replaying.
fast = async { activity :cheap_model, prompt }
slow = async { activity :smart_model, prompt }
timeout = async { sleep 10.minutes; :timed_out }
case first_of(fast, slow, timeout).result
when :timed_out then activity :notify_oncall
else activity :save, _1
end
cancel_the_others
The timer is durable. The race survives a deploy.
class Approval < Workflow
update def answer(value) = @answer = value
query def status = @answer ? :answered : :waiting
def execute
wait_until(timeout: 7.days) { @answer }
activity(@answer ? :deploy : :escalate)
end
end
No polling, no cron, no column. Seven days cost nothing.
| What happened | Decision |
|---|---|
| Timeout, 503, rate limit | Retry |
| Bad URL, invalid card | Non-retryable: stop now |
| The record is gone | Success: nothing left to do |
| Task ran, and the answer is “no” | A result, not an error |
raise RetryLater.new("rate limited", type: "RateLimited", retry_in: 90.seconds)
Submit work to another system. Check once a minute until it's done.
build_id = activity :submit_build, image
def check_build(build_id) # activity
raise NotDoneYet unless build_service.status(build_id) == :done
end
activity :check_build, build_id,
retry: { interval: 1.minute, backoff: 1.0, max_attempts: :unlimited },
schedule_to_close: 45.minutes # the real deadline
The retry policy is the wait.
≈ 11 events
per look: activity, timer, two workflow tasks
45 looks ≈ 495 events
3 events
Scheduled, Started, Completed, for all attempts together
Retries never land in history
It's Temporal's documented pattern for infrequent polling. The cost: a healthy wait looks like a failing activity.
class SendEmail < Workflow
def execute(id) = activity :send_email, id
end
start SendEmail, id: "send-email:#{order_id}", if_running: :use_existing
One workflow, one activity. The id gives you deduplication.
We use Temporal as our background job server.
schedule :refresh_images, every: 1.hour, overlap: :buffer_one
| Previous run still going? | Overlap policy |
|---|---|
| Drop this tick | Skip (default) |
| Keep one waiting, drop the rest | BufferOne |
| Queue them all | BufferAll |
| Stop it and start this one | CancelOther, TerminateOther |
| Run both | AllowAll |
Sleeps in tests? Make durations an input.
Worker.new(max_cached_workflows: 0)
Rolling a deploy empties the cache anyway. I want that path to be the only path.
Act 4
Code changes. History doesn't. A run in flight must replay on your new code.
Before
activity :build_report
activity :email_report
After
activity :notify_started
activity :build_report
activity :email_report
NondeterminismError: [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'build_report' does not match activity type of activity command 'notify_started'
if patched?("notify-started")
activity :notify_started
end
activity :build_report
activity :email_report
1. Old runs still alive
if patched?("notify-started")
activity :notify_started
end
activity :build_report
activity :email_report
2. Old runs all finished
deprecate_patch("notify-started")
activity :notify_started
activity :build_report
activity :email_report
3. Runs from step 1 finished
activity :notify_started
activity :build_report
activity :email_report
if| Cancel | Terminate | |
|---|---|---|
| Workflow code runs? | Yes, if it listens | Never |
| Cleanup possible? | If you wrote it | No |
| Running activity stops? | Only if it heartbeats | No |
An activity learns about cancel only from a heartbeat reply.
An agent turn that runs for 2 hours? It finds out in 2 hours.
A word from the sponsor of rock-solid workflows
class Approval < Workflow
def execute
@dm = activity :post_slack_dm # where the question is
wait_until { @answer }
end
update def answer(value)
@answer = value
@dm # so we can edit that message
end
end
answer returns the DM. We edit it
answer returns nil. The DM never changes
No error, no warning. The one thing you were promised can't happen.
class Approval < Workflow
def execute
@dm = activity :post_slack_dm
sleep 0.001 # a timer is a command. sdk-rust#1606
wait_until { @answer }
end
update def answer(value)
@answer = value
@dm
end
end
The step after the activity is no longer empty, so the SDK doesn't merge it on replay.
A 1 ms sleep holding up a durable execution platform.
And now it's in the histories. Removing it needs a patch.
Same workflow, same moment. Two different states.
sdk-rust#1623. In our tests: 3 runs in 8. A human is too slow to hit the gap. Automation isn't.
“The current chunker is complex, brittle, and has already introduced non-determinism.”
Temporal's own PR, temporalio/sdk-rust #1659
Fair play: we're on a pre-1.0 pin from June, 224 commits behind. The SDK has since gone 1.0. It's still open.
| Zero-downtime | Backwards compatibility | Idempotency | |
|---|---|---|---|
| Workflow code | replayed after every restart | new code, old histories: patches | – |
| Activity code | killed mid-run by a deploy | retried: new code, old arguments | runs at least once |
| Input/activity/update payloads | – | old JSON for the retention period | – |
| Timeouts | must outlast a restart | – | a timeout means a retry |
Every small change: check all twelve cells.
# I want to write one row.
class RecordRunStart < Activity
def execute(run_id) = db.update(run_id, started_at: now)
end
activity :record_run_start, run_id,
timeout: 30.seconds, retry: { max_attempts: 5 } if patched?("record-run-start")
One UPDATE: an activity, a timeout, a retry policy, a patch.
Act 5
const files = await session.run("count files")
const doubled = await session.run(`double ${files}`)
It worked. Survived crashes, restarts, replay, cache off.
const bugs = (await listIssues(repo)).filter(i => i.labels.includes("bug"))
for (const bug of bugs) { // which bug?
let attempt = 0 // which attempt?
let verdict
do {
await fix(bug, ++attempt)
verdict = await review(bug) // what did the review say?
} while (!verdict.ok)
}
What would a query even query?
An embedded engine can run the JS. It can't tell you what it is running.
The answers live in VM stack frames. You'd be building a debugger. We never built one.
{ "steps": [
{ "name": "list", "call": "list_issues", "args": { "repo": "input.repo" } },
{ "map": { "in": "steps.list.output.filter(i, 'bug' in i.labels)", "as": "bug",
"body": [
{ "doWhile": { "cond": "!steps.review.output.ok", "body": [
{ "name": "fix", "call": "fix", "args": { "issue": "bug" } },
{ "name": "review", "call": "review", "args": { "issue": "bug" } } ] } }
] } }
] }
Structure: JSON. Leaves: CEL.
class InterpreterWorkflow < Workflow
query def progress = @progress
def execute(plan, input) = walk(plan.steps, Env.new(input))
def walk(steps, env)
steps.each do |step|
case step
when Call
args = Cel.eval(step.args, env) # right here, in the workflow
@progress[step.path] = :running
env.steps[step.name] = activity(step.op, args)
@progress[step.path] = :done
when If then walk(Cel.eval(step.cond, env) ? step.then : [], env)
end
end
end
end
steps.list.output.filter(i, 'bug' in i.labels)Date.now to call7 issues, 4 bugsreview ok after 1 attemptreview ok after 2 attemptslast review: "tests fail"Step identity = path + loop iteration. Rebuilt by replay, for free.
Promise.all, race, any, allSettled, for await, AbortController, fire-and-forget, a semaphore… Each needs its own syntax and its own pictureOur DSL stops at parallel map. Every step up needs a new picture.
.all(), tens of secondspankowecki.pl · github.com/paneq
Appendix
gem temporalio 1.10.1, on the SDK test server. Not something I use at work
class Charge < Temporalio::Activity::Definition
def execute(amount)
raise Temporalio::Error::ApplicationError.new(
'card declined', type: 'CardDeclined', non_retryable: true) if amount < 0
"charged #{amount}"
end
end
class ChargeWorkflow < Temporalio::Workflow::Definition
def execute(amount)
Temporalio::Workflow.execute_activity(Charge, amount,
start_to_close_timeout: 30,
retry_policy: Temporalio::RetryPolicy.new(
initial_interval: 1, backoff_coefficient: 2.0, max_interval: 60,
max_attempts: 5, non_retryable_error_types: ['InvalidCard']))
end
end
W = Temporalio::Workflow
slots = W::SizedQueue.new(limit)
futures = items.map do |item|
W::Future.new do
slots.push(true)
begin
W.execute_activity(Work, item, start_to_close_timeout: 30)
ensure
slots.pop
end
end
end
W::Future.all_of(*futures).wait
cancellation, cancel = Temporalio::Cancellation.new(W.cancellation)
act = W::Future.new { W.execute_activity(Work, 1, start_to_close_timeout: 30, cancellation:) }
timer = W::Future.new { W.sleep(3600, cancellation:); :timeout }
W::Future.any_of(act, timer).wait
cancel.call
def execute
W.sleep(3600)
rescue Temporalio::Error => e
raise unless Temporalio::Error.canceled?(e)
W.execute_activity(Cleanup, start_to_close_timeout: 30,
cancellation: Temporalio::Cancellation.new) # detached
raise
end
Temporalio::Testing::WorkflowEnvironment.start_time_skipping do |env|
# a workflow sleeping for a day finishes right away
end
require 'temporalio/worker/workflow_replayer'
Temporalio::Worker::WorkflowReplayer.new(workflows: [MyWorkflow])
.replay_workflow(handle.fetch_history)
| Limit | Warns | Fails |
|---|---|---|
| History events | 10,240 | 51,200 |
| History size | 10 MB | 50 MB |
| Single payload | 512 KB | 2 MB |
| Pending activities or children | 2,000 |
Polling guide: under 1s, loop in an activity and heartbeat. Over 1 min, use retries. Complex: child workflow and Continue-As-New.