Skip to content

Commit 5cc2dee

Browse files
authored
fix(workflow): spawn run Bots with bounded concurrency (#3286) (#3287)
Written-by: Dev Fixes #3286 Owner: Dev Reviewer: Reviewer ## What changed A run created its node Bots one at a time, so a six-node line could not fit the 60s batch deadline (`SPAWN_DEADLINE_MS`) and a five-node line was a coin flip. `spawnAll` now creates up to `SPAWN_CONCURRENCY = 4` at once (the width is a parameter tests can inject). A refused spawn starts no further Bot, the ones already in flight are awaited and still land in `error.spawned` (creation order), and the returned map keeps the graph's node order whatever order the host answers in. The deadline sentence's "needs about Ns" estimate now counts waves, and progress names the last-started node the host has not answered, so #3282's node name and reason still work with several spawns in flight. ## Before / after - Before: serial 6 × ~11s ≈ 66s > 60s (wf-1cdf6ec5 failed three times); 5 × ~11s ≈ 55s, ~5s of slack (wf-7ed167b6 failed once at 10:45Z). - After: ceil(6/4) = 2 waves × ~11s ≈ 22s; ceil(5/4) = 2 waves ≈ 22s. The new test drives a fake clock with 10s per spawn: six nodes finish in 20s, with at most 4 in flight. ## Verification at the tip Tip SHA: 534c2c8 Ran: - `cd plugins/workflow && DSH_HARNESS=/opt/flybot node --import ./test/resolve.mjs --test "test/*.test.js"` — 544 tests, 544 pass, 0 fail. - `node core/scripts/build-client.mjs --check` — ok (no client change). - `node scripts/ds-bot-patches.mjs check` — ok, 10 patches. - `node .github/scripts/changelog.mjs check` — ok. - `node scripts/lint-plugins.mjs` and oxlint over `core` — 0 errors (warnings are pre-existing). Not run (and why): - Full `npm run verify` could not complete on this box: `core` here has no `dev/harness` oxlint install and `arch-docs` needs `git` + `origin/main`, and this host has no `git`. The affected workflow suite, the client check, the patch check, the changelog check and lint were run as above; `core/` is untouched. ## Red first Source unchanged, new test only (`plugins/workflow/test/parallel-spawn.test.js`): 1 of 3 pass, 2 fail — `never more than four spawns in flight: 1` (the serial loop) and `two spawns are in flight: actual ["node-1"]`. The same two tests pass after the change. ## Checkpoint <!-- flybot:checkpoint --> ```json { "pr": 3287, "claim": "Dev", "issue": 3286, "summary": "spawnAll creates run Bots four at a time instead of one after another, so a six-node lane needs two waves (~22s) and fits the 60s batch deadline. A refused spawn starts no new Bot, awaits the ones in flight, and error.spawned lists every Bot made in creation order. The returned map follows the graph's node order, and the timeout sentence's estimate counts waves.", "files": ["plugins/workflow/src/ephemeral.js", "plugins/workflow/src/service.js", "plugins/workflow/test/parallel-spawn.test.js", "docs/subsystems/workflow.md", "changelog.d/3286.fixed.md"], "checks": { "ran": "cd plugins/workflow && DSH_HARNESS=/opt/flybot node --import ./test/resolve.mjs --test 'test/*.test.js'", "result": "green", "at": "534c2c860eb0c8470cb2082ee437b5d75042cc6f" }, "next": "none — ready for review" } ``` <!-- /flybot:checkpoint -->
1 parent 747e009 commit 5cc2dee

5 files changed

Lines changed: 190 additions & 24 deletions

File tree

‎changelog.d/3286.fixed.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
A Workflow now creates its run Bots four at a time instead of one after another, so a six-node line starts in about 20 seconds instead of about 66 and no longer misses the 60-second batch deadline a slow host used to hit ([#3286](https://github.com/ThinkFlowLab/FlyBot/issues/3286)). If the host refuses one node, the line stops asking for new Bots, waits for the ones already in flight, and releases every Bot it did create; the run still maps the graph's nodes to their Bots in the graph's own order.

‎docs/subsystems/workflow.md‎

Lines changed: 2 additions & 2 deletions
Large diffs are not rendered by default.

‎plugins/workflow/src/ephemeral.js‎

Lines changed: 46 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,24 +43,58 @@ export function runCaps(callerBotId, authorBotId) {
4343
return [...new Set(ids)]
4444
}
4545

46-
export async function spawnAll(nodes, roster, spawn, workflowModel = '', caps = {}) {
47-
const made = []
46+
// #3286: a host answers a spawn in about ten seconds, so a six-node lane created one
47+
// Bot at a time needs ~66s and cannot fit the 60s batch deadline around a start. Four
48+
// at a time finishes the same lane in two waves (~20s); a caller may pass a narrower
49+
// or wider width as the last argument (tests use it to hold the waves still).
50+
export const SPAWN_CONCURRENCY = 4
51+
52+
export async function spawnAll(nodes, roster, spawn, workflowModel = '', caps = {}, concurrency = SPAWN_CONCURRENCY) {
53+
const list = Array.isArray(nodes) ? nodes : []
54+
const width = Number.isInteger(concurrency) && concurrency > 0 ? concurrency : SPAWN_CONCURRENCY
4855
const capping = runCaps(caps.callerBotId, caps.authorBotId)
49-
try {
50-
const ephemeral = {}
51-
for (const node of nodes) {
56+
// `made` is the order the host answered in: it is what `error.spawned` reports, so a
57+
// failed start releases in the order the Bots came up, not the order they were asked for.
58+
const made = []
59+
const byIndex = new Map()
60+
let next = 0
61+
let failure = null
62+
63+
const create = async () => {
64+
for (;;) {
65+
// Checked before taking the next index, so a refusal stops new spawns at once; the
66+
// ones already in flight are still awaited below and still land in `made`.
67+
if (failure !== null) return
68+
const index = next
69+
next += 1
70+
if (index >= list.length) return
71+
const node = list[index]
5272
const spec = nodeConfig(node, roster, workflowModel)
5373
if (capping.length > 0) spec.cappedBy = capping
54-
const id = await spawn(spec)
55-
if (typeof id !== 'string' || id === '') throw new Error('The run could not start a Bot')
74+
let id
75+
try {
76+
id = await spawn(spec)
77+
if (typeof id !== 'string' || id === '') throw new Error('The run could not start a Bot')
78+
} catch (error) {
79+
if (failure === null) failure = error
80+
return
81+
}
5682
made.push(id)
57-
ephemeral[node.id] = id
83+
byIndex.set(index, id)
5884
}
59-
return ephemeral
60-
} catch (error) {
61-
error.spawned = made
62-
throw error
6385
}
86+
87+
const workers = []
88+
for (let i = 0; i < Math.min(width, list.length); i += 1) workers.push(create())
89+
await Promise.all(workers)
90+
if (failure !== null) {
91+
failure.spawned = made.slice()
92+
throw failure
93+
}
94+
// Keys follow the graph's nodes, whatever order the host answered in.
95+
const ephemeral = {}
96+
for (let i = 0; i < list.length; i += 1) ephemeral[list[i].id] = byIndex.get(i)
97+
return ephemeral
6498
}
6599

66100
// Returns the ids whose release failed: that Bot is still there, so the caller

‎plugins/workflow/src/service.js‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import { randomBytes } from 'node:crypto'
66
import { copyFileSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
77
import { join } from 'node:path'
8-
import { releaseAll, spawnAll } from './ephemeral.js'
8+
import { SPAWN_CONCURRENCY, releaseAll, spawnAll } from './ephemeral.js'
99
import {
1010
chainLabel, cleanLine, cleanPorts, cleanPrompt, cleanTools, completeNode, cutCodePoints, doneCount, edgeOutputs, failNode, freshStatus,
1111
layerMarks, firstBranchValue, missingProviders, missingVerdicts, nodeById, normalizeGraph, orderedIds, readStepResult, resolveInputs, retryNode,
@@ -503,12 +503,13 @@ export function createWorkflowService({
503503
const waited = current.startedAt > 0 ? now() - current.startedAt : 0
504504
rest.push(`node ${current.label} still had no Bot${waited > 0 ? ` after ${formatMs(waited)}` : ''}`)
505505
}
506-
// The average turns "slow" into a number the owner can act on: six nodes at eleven seconds
507-
// each cannot fit a sixty-second deadline, whatever the settings say.
506+
// The average turns "slow" into a number the owner can act on: the lane needs as many
507+
// waves of SPAWN_CONCURRENCY as its node count requires (#3286).
508508
const average = created.length > 0 ? created.reduce((sum, one) => sum + (one.ms > 0 ? one.ms : 0), 0) / created.length : 0
509509
if (average > 0 && total > 0) {
510-
const needed = Math.round((average * total) / 1000)
511-
if (needed > seconds) rest.push(`a lane of ${total} nodes needs about ${needed}s on this host at ${formatMs(average)} per Bot, past the ${seconds}s deadline`)
510+
const waves = Math.ceil(total / SPAWN_CONCURRENCY)
511+
const needed = Math.round((average * waves) / 1000)
512+
if (needed > seconds) rest.push(`a lane of ${total} nodes needs about ${needed}s on this host at ${formatMs(average)} per Bot with ${SPAWN_CONCURRENCY} spawned at a time, past the ${seconds}s deadline`)
512513
}
513514
return rest.length === 0
514515
? `the host did not create the run Bots within ${seconds}s`
@@ -1411,23 +1412,28 @@ export function createWorkflowService({
14111412
// this run may use; the host intersects them with each node's `tools`.
14121413
// #3282: the loop reports the node it is on and the Bots already made, so the deadline
14131414
// below can name the node that never answered instead of one bare sentence.
1414-
const progress = { total: item.nodes.length, created: [], current: null }
1415+
// #3286: with several spawns in flight, "the node the host is on" is a set, not one
1416+
// slot. The message names the node started last that the host has not answered yet.
1417+
const progress = { total: item.nodes.length, created: [], current: null, pending: new Map() }
14151418
const spawnNode = async (spec) => {
14161419
const startedAt = now()
14171420
const nodeId = String(spec?.nodeId ?? '')
14181421
const nodeName = String(spec?.name ?? '')
1419-
progress.current = { nodeId, nodeName, label: nodeLabel({ nodeId, nodeName }), startedAt }
1422+
const label = nodeLabel({ nodeId, nodeName })
1423+
progress.pending.set(nodeId, { nodeId, nodeName, label, startedAt })
1424+
progress.current = progress.pending.get(nodeId)
14201425
try {
14211426
const id = await spawn(spec)
14221427
// A host that answers an empty id is a refusal too, and it has to name the node the
14231428
// way a thrown one does: spawnAll() would otherwise refuse it without a node context.
14241429
if (typeof id !== 'string' || id === '') throw new Error('the host returned no Bot id')
1425-
progress.created.push({ nodeId, nodeName, label: progress.current.label, ms: Math.max(0, now() - startedAt) })
1426-
progress.current = null
1430+
progress.created.push({ nodeId, nodeName, label, ms: Math.max(0, now() - startedAt) })
14271431
return id
14281432
} catch (error) {
1429-
progress.current = null
14301433
throw spawnFailure(error, spec, item.id)
1434+
} finally {
1435+
progress.pending.delete(nodeId)
1436+
progress.current = [...progress.pending.values()].at(-1) ?? null
14311437
}
14321438
}
14331439
ephemeral = await boundedSpawn(spawnAll(item.nodes, bots() ?? [], spawnNode, item.model ?? '', {
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
// #3286: a run creates its node Bots with bounded concurrency. A host answers a
2+
// spawn in about ten seconds, so a six-node lane built one Bot at a time needs
3+
// ~66s and cannot fit the 60s batch deadline the service puts around a start.
4+
// Four at a time finishes the same lane in two waves (~20s).
5+
//
6+
// The host is a fake clock: a spawn resolves only when the test moves time to its
7+
// due moment, so the timing assertions are about how many waves `spawnAll` needs,
8+
// not about how fast this machine is.
9+
import assert from 'node:assert/strict'
10+
import { test } from 'node:test'
11+
import * as ephemeralModule from '../src/ephemeral.js'
12+
13+
const NODES = Array.from({ length: 6 }, (_, index) => ({
14+
id: `node-${index + 1}`,
15+
name: `Node ${index + 1}`,
16+
role: 'dev',
17+
prompt: `Do step ${index + 1}.`,
18+
}))
19+
const DELAY = 10_000
20+
21+
const tick = () => new Promise(done => setImmediate(done))
22+
23+
function fakeHost(delayFor = () => DELAY) {
24+
let now = 0
25+
let active = 0
26+
let maxActive = 0
27+
const calls = []
28+
const queue = []
29+
const spawn = (spec) => {
30+
active += 1
31+
maxActive = Math.max(maxActive, active)
32+
const entry = { spec, id: `eph-${spec.nodeId}`, due: now + delayFor(spec) }
33+
calls.push(entry.spec.nodeId)
34+
return new Promise((resolve) => {
35+
entry.finish = () => {
36+
active -= 1
37+
resolve(entry.id)
38+
}
39+
queue.push(entry)
40+
})
41+
}
42+
async function advance() {
43+
const due = Math.min(...queue.map(entry => entry.due))
44+
now = due
45+
const ready = queue.filter(entry => entry.due <= due)
46+
for (const entry of ready) queue.splice(queue.indexOf(entry), 1)
47+
for (const entry of ready) entry.finish()
48+
await tick()
49+
}
50+
return {
51+
spawn,
52+
calls,
53+
advance,
54+
get now() { return now },
55+
get maxActive() { return maxActive },
56+
get pending() { return queue.length },
57+
}
58+
}
59+
60+
// Drives the fake clock until `spawnAll` settles, failing loudly if it waits on
61+
// a spawn that the test never released.
62+
async function run(batch, host) {
63+
let done = false
64+
batch.then(() => { done = true }, () => { done = true })
65+
while (!done) {
66+
await tick()
67+
if (done) break
68+
if (host.pending === 0) throw new Error('spawnAll waits with no spawn in flight')
69+
await host.advance()
70+
}
71+
return batch
72+
}
73+
74+
test('#3286: spawns run four at a time and a six-node lane fits the 60s batch deadline', async () => {
75+
const host = fakeHost()
76+
const batch = ephemeralModule.spawnAll(NODES, [], host.spawn)
77+
const ephemeral = await run(batch, host)
78+
79+
assert.equal(host.maxActive, 4, `never more than four spawns in flight: ${host.maxActive}`)
80+
assert.equal(Object.keys(ephemeral).length, 6, 'every node got a Bot')
81+
// Six nodes at 10s each: serial would be 60s (the old failure) and four at a
82+
// time is 20s. The bound keeps a slow machine from passing by luck.
83+
assert.ok(host.now < 60_000, `the whole batch took ${host.now}ms of host time, past the 60s deadline`)
84+
assert.ok(host.now <= 3 * DELAY, `two waves at ${DELAY}ms were expected, the batch took ${host.now}ms`)
85+
assert.equal(ephemeralModule.SPAWN_CONCURRENCY, 4, 'the default width is four')
86+
})
87+
88+
test('#3286: a failed spawn stops new starts, lets the ones in flight land, and reports what was made', async () => {
89+
const calls = []
90+
const pending = []
91+
const spawn = (spec) => {
92+
calls.push(spec.nodeId)
93+
return new Promise((resolve, reject) => pending.push({ resolve, reject }))
94+
}
95+
const batch = ephemeralModule.spawnAll(NODES, [], spawn, '', {}, 2)
96+
const failed = batch.then(() => null, error => error)
97+
await tick()
98+
assert.deepEqual(calls, ['node-1', 'node-2'], 'two spawns are in flight')
99+
100+
pending[0].resolve('eph-node-1')
101+
pending[1].resolve('eph-node-2')
102+
await tick()
103+
assert.deepEqual(calls, ['node-1', 'node-2', 'node-3', 'node-4'], 'both workers took the next nodes')
104+
105+
// The third node the host answers is a refusal. The fourth is still in flight:
106+
// it must land, and no fifth or sixth spawn may start.
107+
pending[2].reject(new Error('the host could not create the coder'))
108+
await tick()
109+
assert.deepEqual(calls, ['node-1', 'node-2', 'node-3', 'node-4'], 'no new spawn starts after the refusal')
110+
pending[3].resolve('eph-node-4')
111+
112+
const error = await failed
113+
assert.equal(error?.message, 'the host could not create the coder', 'the host reason is carried')
114+
assert.deepEqual(error.spawned, ['eph-node-1', 'eph-node-2', 'eph-node-4'], 'exactly the Bots that were made, in the order they landed')
115+
assert.deepEqual(calls, ['node-1', 'node-2', 'node-3', 'node-4'], 'the other two nodes were never asked for')
116+
})
117+
118+
test('#3286: the result keeps the graph order even when the Bots land out of order', async () => {
119+
const delays = [50_000, 10_000, 20_000, 30_000, 40_000, 5_000]
120+
const host = fakeHost(spec => delays[Number(spec.nodeId.slice('node-'.length)) - 1])
121+
const ephemeral = await run(ephemeralModule.spawnAll(NODES, [], host.spawn), host)
122+
123+
assert.deepEqual(Object.keys(ephemeral), NODES.map(node => node.id), 'the keys follow the nodes, not the answers')
124+
for (const node of NODES) assert.equal(ephemeral[node.id], `eph-${node.id}`)
125+
})

0 commit comments

Comments
 (0)