Golem parallel workers scala

From golemcloud/golem · View interactive version

Golem parallel workers scala is an AI agent skill from the GitHub repository golemcloud/golem. Fan out work to multiple parallel agents and collect results in a Scala Golem project. Use when the user asks about parallel execution, fan-out/fan-in, spawning child agents for parallel work, forking, or aggregating results from multiple agents.

How to use this skill

Skill file

Parallel Workers — Fan-Out / Fan-In (Scala)

Overview

Golem agents admit invocations sequentially. Futures and asynchronous I/O can overlap within one invocation; this is not CPU-thread parallelism. Distribute work across multiple agent instances for independently scheduled execution. This skill covers two approaches:

  1. Child agents via codegen-generated XClient.upsert(id) — spawn separate agent instances, dispatch work, and collect results
  2. HostApi.fork() — clone the current agent at the current execution point for lightweight parallel execution

Approach 1: Child Agent Fan-Out

Spawn child agents, dispatch work, and collect results using Future.sequence or Golem promises.

Basic Pattern with Future.sequence

import golem.*
import golem.runtime.annotations.{agentDefinition, agentImplementation}

import scala.concurrent.Future
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue

@agentDefinition()
trait Coordinator extends BaseAgent {
  class Id()
  def fanOut(items: List[String]): Future[List[String]]
}

@agentImplementation()
class CoordinatorImpl() extends Coordinator {
  override def fanOut(items: List[String]): Future[List[String]] = {
    // Spawn one child per item and call concurrently
    val futures = items.zipWithIndex.map { case (item, i) =>
      val child = WorkerClient.upsert(i)
      child.process(item)
    }

    // Wait for all children to finish
    Future.sequence(futures)
  }
}

@agentDefinition()
trait Worker extends BaseAgent {
  class Id(val id: Int)
  def process(data: String): Future[String]
}

@agentImplementation()
class WorkerImpl(private val id: Int) extends Worker {
  override def process(data: String): Future[String] = {
    Future.successful(s"processed-$data")
  }
}

Fire-and-Forget with Promise Collection

For long-running work, trigger children with fire-and-forget and collect results via Golem promises:

import golem.HostApi
import golem.HostApi.PromiseId
import zio.blocks.schema.Schema

case class WorkResult(value: String) derives Schema
case class PromiseRef(agent: golem.AgentId, fingerprintHigh: String, fingerprintLow: String,
                      oplogIndex: String) derives Schema {
  def toHost: PromiseId = HostApi.PromiseIdLiteral(
    agent,
    HostApi.UuidLiteral(
      scala.scalajs.js.BigInt(fingerprintHigh), scala.scalajs.js.BigInt(fingerprintLow)),
    scala.scalajs.js.BigInt(oplogIndex))
}

object PromiseRef {
  def fromHost(pid: PromiseId): PromiseRef = PromiseRef(
    golem.host.js.JsAgentId.toAgentId(pid.agentId),
    pid.fingerprint.highBits.toString,
    pid.fingerprint.lowBits.toString,
    pid.oplogIdx.toString)
}

@agentDefinition()
trait RegionWorker extends BaseAgent {
  class Id(val region: String)
  def runReport(promise: PromiseRef): Future[Unit]
}

@agentImplementation()
class CoordinatorImpl() extends Coordinator {
  override def dispatchAndCollect(regions: List[String]): Future[List[String]] = {
    // Create one promise per child
    val promiseIds = regions.map(_ => HostApi.createPromise())

    // Fire-and-forget: trigger each child with its promise ID
    val accepted = regions.zip(promiseIds).map { case (region, pid) =>
      val child = RegionWorkerClient.upsert(region)
      child.runReport.trigger(PromiseRef.fromHost(pid))
    }

    // Observe dispatch failures before waiting on promises that may never complete.
    Future.sequence(accepted).flatMap { _ =>
      Future.traverse(promiseIds) { pid =>
        HostApi.awaitPromiseJson[WorkResult](pid).map(_.value)
      }
    }
  }
}

@agentImplementation()
class RegionWorkerImpl(private val region: String) extends RegionWorker {
  override def runReport(promise: PromiseRef): Future[Unit] = {
    val result = WorkResult(s"Report for $region: OK")
    HostApi.completePromiseJson(promise.toHost, result)
    Future.successful(())
  }
}

For this variant, declare dispatchAndCollect(regions: List[String]): Future[List[String]]

on Coordinator instead of fanOut. HostApi.PromiseId is a JavaScript facade,

not a schema DTO: pass PromiseRef across RPC and reconstruct the host value.

Acceptance does not guarantee worker success; production workflows also need an

explicit worker failure or timeout protocol to avoid waiting forever.

Chunked Fan-Out

Batch children to limit concurrency:

override def fanOutChunked(items: List[String]): Future[List[String]] = {
  val chunks = items.grouped(5).toList

  chunks.foldLeft(Future.successful(List.empty[String])) { (accFut, chunk) =>
    accFut.flatMap { acc =>
      val futures = chunk.zipWithIndex.map { case (item, i) =>
        WorkerClient.upsert(i).process(item)
      }
      Future.sequence(futures).map(acc ++ _)
    }
  }
}

Error Handling

Use Future.traverse with recover for partial failure handling:

override def fanOutWithErrors(items: List[String]): Future[(List[String], List[String])] = {
  val futures = items.zipWithIndex.map { case (item, i) =>
    WorkerClient.upsert(i).process(item)
      .map(Right(_))
      .recover { case e: Throwable => Left(s"Item $item failed: ${e.getMessage}") }
  }

  Future.sequence(futures).map { results =>
    val successes = results.collect { case Right(v) => v }
    val failures = results.collect { case Left(e) => e }
    (successes, failures)
  }
}

Approach 2: `HostApi.fork()`

HostApi.fork() clones the current agent at the current execution point, creating a new agent instance with the same state, a new agent ID and no key. Only a durable agent can fork, and the forked agent is durable too. Use Golem promises to synchronize between the original and forked agents.

Basic Fork Pattern

import golem.HostApi
import golem.HostApi.{ForkResult, PromiseId}

override def parallelCompute(): Future[String] = {
  val promiseId = HostApi.createPromise()

  HostApi.fork() match {
    case ForkResult.Original(_) =>
      // Wait for the forked agent to complete the promise
      HostApi.awaitPromise(promiseId).map { bytes =>
        val forkedResult = new String(bytes, "UTF-8")
        s"Combined: original + $forkedResult"
      }

    case ForkResult.Forked(_) =>
      // Do work in the forked copy
      val result = "forked-result"
      HostApi.completePromise(promiseId, result.getBytes("UTF-8"))
      Future.successful("forked done") // Only seen by the forked agent
  }
}

Multi-Fork Fan-Out

Fork multiple times for N-way parallelism:

override def multiFork(n: Int): Future[List[String]] = {
  val promiseIds = (0 until n).map(_ => HostApi.createPromise()).toList

  for (i <- 0 until n) {
    HostApi.fork() match {
      case ForkResult.Original(_) =>
        // Continue to next fork

      case ForkResult.Forked(_) =>
        // Each forked agent does its slice of work
        val output = s"result-from-fork-$i"
        HostApi.completePromise(promiseIds(i), output.getBytes("UTF-8"))
        return Future.successful(Nil) // Forked agent exits here
    }
  }

  // Original agent collects all results
  val futures = promiseIds.map { pid =>
    HostApi.awaitPromise(pid).map(bytes => new String(bytes, "UTF-8"))
  }
  Future.sequence(futures)
}

When to Use Which Approach

| Criteria | Child Agents | HostApi.fork() |

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

| Work is independent and stateless | ✅ Best fit | Works but overkill |

| Need to share current state with workers | ❌ Must pass via args | ✅ Forked copy inherits state |

| Workers need persistent identity | ✅ Each has own ID | ❌ Each forked agent gets a new agent ID and no key |

| Number of parallel tasks is dynamic | ✅ Spawn as many as needed | ✅ Fork in a loop |

| Need simple error isolation | ✅ Child failure doesn't crash parent | ⚠️ Forked agent shares oplog lineage |

Key Points

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.