From 9964ce7316b3d7d0f2c63d23c7e6d5e8a8f15936 Mon Sep 17 00:00:00 2001 From: FlyBot Dev-3 Date: Tue, 10 Nov 2026 00:42:36 +0000 Subject: [PATCH 1/2] fix(workflow): drain the queue when a load-time reap ends a run A run the host left 'running' comes back from the store, and reap() ends it 'host-ended'. That is a terminal transition like a run finishing a step, but the drain lived only on the finish paths, so the card parked behind it stayed in lane.queue with a free slot and started only on the next assign (#2752). Drain on the load-time reap instead. The takeover reap keeps its own rule: it is a detached promise, and a drain there races the assign that triggered the takeover and starts two cards past maxConcurrent (#2704 F2). --- ...2752-queued-card-after-failed-run.fixed.md | 1 + docs/subsystems/workflow.md | 2 +- plugins/workflow/src/service.js | 13 ++-- ...ueued-card-starts-after-failed-run.test.js | 64 +++++++++++++++++++ 4 files changed, 73 insertions(+), 7 deletions(-) create mode 100644 changelog.d/2752-queued-card-after-failed-run.fixed.md create mode 100644 plugins/workflow/test/queued-card-starts-after-failed-run.test.js diff --git a/changelog.d/2752-queued-card-after-failed-run.fixed.md b/changelog.d/2752-queued-card-after-failed-run.fixed.md new file mode 100644 index 000000000..4fb8484ba --- /dev/null +++ b/changelog.d/2752-queued-card-after-failed-run.fixed.md @@ -0,0 +1 @@ +A card queued behind a run that ended **failed** now starts on its own: the load-time reap that ends a run a dead host left `running` drains the lane's queue the way any other terminal transition does, instead of leaving the card parked with a free slot until the next assign. See [#2752](https://github.com/ThinkFlowLab/FlyBot/issues/2752). diff --git a/docs/subsystems/workflow.md b/docs/subsystems/workflow.md index c857e0279..897712b1f 100644 --- a/docs/subsystems/workflow.md +++ b/docs/subsystems/workflow.md @@ -59,7 +59,7 @@ Everything in `plugins/workflow/`: the graph rules, the run store, the matcher, 1. Friends' Bots are not nodes. A `remote` Bot is refused by create, define and the matcher. 2. The canvas and the run share one graph: nodes, edges and positions. A drag commits `workflow/graph`, but only while **Edit** is on — a factory preset is copied first (#1378). A wire or a reconnect that would list a pair the graph already carries commits nothing new, because `normalizeGraph` refuses a graph that lists one pair twice and then saves none of it: unguarded, the plane would show no edge, no change and only a save error (#2163). Status highlighting reads that same graph. Replacing edges does not recompute who is already running. The Settings canvas paints that graph on the same 960px design plane, scaled to the width the settings page gives it, so the canvas is not a second scroll container inside the page's own scroll; its pointer deltas are divided by the scale, and its wires keep a stronger stroke than a plain divider so an edge can be followed at that size (#1483). While another dsh holds the Bot team the host is read-only (`roster.readOnly`): the page still reads through `workflow/state`, keeps its controls disabled, and offers no **Edit**, **Add link** or wire port, so it cannot take a change that core would refuse with `bot/read-only` and then drop (#2187). The same window draws the sidebar's workflow list without **New**, the row's **Rename**/**Delete** or **Hand a task to a Workflow**: the list is read-only too, and an `roster.readOnly` that is not a string, or holds only whitespace, counts as writable — trimmed the way `core/src/client/workflows.js:570` trims it (#2200). The Stage a row opens carries the same lock: it prints the host's sentence under `role="status"` and draws no **Hand a task to a Workflow**, no **Re-match**, no **Pause**/**Resume**/**Stop**, no **Edit**/drag palette and no **Reset**, while the row click, **Progress**, **Flow** and viewing a run still work; a writable roster draws every control exactly as before (#2213). Mounting the list in a read-only window still reads `projects` so the Project filter fills, but it sends no `workflow/ingest` for the open cards: ingest is a claim/match write the host refuses, so a reader opening the list writes nothing; a writable window still ingests every open card (#2222). The read-only sentence can also land after the list has mounted — a cold window starts on the empty roster, `ready: false` and no `readOnly` — so the ingest step asks the value the latest render saw rather than the one the mount saw, and it skips the board read and stops between two cards once the window has turned read-only. The Settings page draws no read-only sentence of its own: the host's Settings header already prints one for every page it shows (`core/src/client/settings.js` `bt-read-only`, `role="status"`, `hostText(roster.readOnly)`), and a second copy inside the page said the same thing twice (#2202). -3. **A live run advances only when its ephemeral Bot replies, following the graph's edges in order.** That reply advances the run and may appear on the workflow stage log; it is not delivered into a persistent sidebar Bot conversation (for example Chief). The `workflow-step` send middleware denies those replies after `stepResult` runs. Nodes start only when their forward predecessors finish and edges reach them. **Early termination (#1537, #1538, #1546, #1570, #1571):** When a node completes **or fails**, the run ends immediately with status `done`, sets `run.earlyEnd` to the condition name, and does not advance to successors, take a success-path `loop`, or burn `onFail` recovery attempts. The two markers that report the task itself end it only on a structured signal (#1546): `needs-human` and `already-claimed` must be a declared OUTPUT whose value **equals** the marker, or a whole reply line that is exactly `EARLY-END ` in any case. A step that quotes an issue title, negates the label or reports it absent keeps running. `tip-unchanged` (#1570) and `open-pr` (#1571) accept that same structured signal — in a declared OUTPUT the value counts as a whole word, so a brief that names `data-open-project` is not `open-pr` (#1866) — and also honor their prose fallbacks (`tip unchanged` / `unchanged tip`, `open PR already` / `already has an open PR` / `has an open PR` / `found an open PR`), so a Bot that forgets the structured marker cannot soft-lock Claim↔Verify on the same tip. See `checkEarlyEnd` in Key files. Factory prompt guidance lives in `EARLY_END_GUIDANCE` (`plugins/workflow/src/template.js`) for Settings graphs that wire Triage / Claim / Verify: Verify must escalate once on an unchanged tip, not re-run the full suite. There is no scripted or seeded run path: `workflow/state` exposes only `live === true` runs — the running ones, plus the last run when it is still `live` and ended `failed` — a failed sibling stays on the stage beside whatever is running now, with `run.failure` (`{ code, at, nodeName?, text? }`) naming what ended it, so the room does not have to open Runs to learn that a run failed (#1493, #1494). The failed sibling is left out when a running run carries the same task id: that is a retry, and the live run keeps the row (#1507). History entries carry the run `id` and the same `failure`, so a Runs row shows when the run ended and why, and a row for a run already on the stage is not listed twice. A run does not create a schedule. `scheduleLabel` is display text. When the host can create Bots, starting a live run (`assign`, `run_workflow`, `ingest`) spawns one ephemeral Bot per node from that node's prompt, role, model and tools, sends it the step from the Main Bot, and removes every instance when the run finishes, fails for good, or is reset. A `failOnce` retry keeps them. They are hidden and left out of the sidebar. Loading the plugin does not spawn Bots for the default workflows. Plugin unload (`dispose`) and the load-time `reap` both end a live run still marked `running`: in-flight nodes are failed, the run is archived as `failed`, and any ephemeral Bot ids are released. A **read-only** host — a second window on the same `DSH_HOME`, the reader `home-lock` describes — does neither: it never ran those runs, so it cannot tell which of them a dead host left behind, and it must not end them, release their step Bots or write its older copy over the writer's store; both calls return without touching the record and the writer's own `reap` decides (#2673). **Taking the lock over is a state change (#2704):** the first call that finds the host writable after this window started read-only — a read, `reap`, `dispose` or any write — re-reads `workflows.json` once before it changes anything, because the copy it loaded predates what the dead window saved, and then runs the same load-time `reap` once on that adopted store. That reap ends the dead window's `running` run as `host-ended` (or heals a `live:true` run whose Bot map is already gone, #1414) and releases its step Bots; `lane.queue` is never touched, so a card that was merely `queued` keeps its place and starts when the lane drains. Only the first such call re-reads — a writer that later loses the lock is still refused, exactly as before. A run already written as `running` with no ephemeral map (an older unload) is healed the same way on the next load (#1414). Loading is also the one moment a run the host left behind is noticed when its ephemeral map is still present: `reap` releases those instances and records the run as `failed`. Nothing resumes it. A run that already ended keeps its own status (#1388). `workflow/reset` stopping one live run ends it the same way before its Bots are released: nodes still `running` become `failed`, so the strip cannot keep painting a run that is over (#1424). A graph edit that drops a node that is still running ends that run the way Stop does: the node is failed, the run is archived `failed`, its node Bots are released, and the queue drains (#1549); an id whose release failed stays named on that archived run, and the next load's `reap` retries it, instead of the edit forgetting it (the #1616 contract). Every wait is bounded (#1530). A dispatch that does not land is not marked handed: the chat names the code and the attempt, and it is retried after a short backoff at most twice, never twice inside one hand-off, so a 429 is not hammered. When it still does not land, the step and the run fail with the reason written into the chat. Each running live step also holds a deadline — its workflow's `stepTimeoutMinutes`, `DEFAULT_STEP_TIMEOUT_MINUTES` (45 minutes) unless the record sets one, an integer from 1 to 120 given at create, through `define_workflow`, or through `workflow/step-timeout` (armed even when the host cannot spawn ephemeral Bots; #1530, #1580); when it expires the node and the run fail as `failed`, the run's ephemeral Bots are released, the chat and `run.failure` say the step's deadline was reached (`step deadline reached (45 min)`, the number its lane set), and `warn` names it once; the line never reads as a reply that did not arrive, because a step still working is killed by the same timer (#1868). The deadline is cleared as soon as the step moves, and by Pause, Reset, delete, `reap`, `dispose` and a Stop that released every Bot; a run the owner paused holds none, and Resume arms it again from that moment. A timer never outlives the run that started it. A reply that matches no running step — its run ended, or the node already moved — is reported through `warn` once per Bot and run instead of being dropped silently. A reply fails that node on a structured signal only: the host's failure notice carries `failure: true`, which the middleware hands `stepResult` as `ok: false` (a caller-set `ok: false` counts too), so an answer that quotes `could not answer your message` or `model call failed` while auditing it advances the step (#2677). An old host without the marker falls back to the notice shapes at the start of the text only (` could not answer your message: …`, ` was stopped before it could answer your message.`, and the bare `could not answer your message` / `The model call failed.` an old host wrote), never a free substring, so an ordinary answer that merely ends in the model-failure wording keeps advancing the step (#2741). A stopped turn is a failed step, with the stop notice as its reason, instead of finishing as done and handing that notice to the next node (#2741). A 429 or rate-limit mention in any other reply does not fail a step. Stop and Reset (`workflow/reset`) follow the same order as `dispose`: they release the run's Bots before the record forgets their ids, and an id whose release failed stays named on the still-live run, so the next Stop, Reset, dispose or load-time `reap` retries it (#1476). A run left that way is marked `paused` and `releasePending` and shows as Paused: it hands off no further node, `resume` is refused with an error, and Stop again is the retry. It also keeps the deadline of the node it was on — the one paused state that holds one — and a graph save re-syncs timers without taking it away (a save that cleared it left the run holding its slot with nothing left to free it); the deadline releases again there, ends the run as `paused-expired` and frees the slot, re-arming itself while a Bot still will not go (#2453, P-560). A whole-workflow Reset that could not release every Bot freezes every run it did not reset, because each of them has lost the ids whose release did go. The markers go away when the run ends: Stop again, `dispose`, `reap`, or its own completion. +3. **A live run advances only when its ephemeral Bot replies, following the graph's edges in order.** That reply advances the run and may appear on the workflow stage log; it is not delivered into a persistent sidebar Bot conversation (for example Chief). The `workflow-step` send middleware denies those replies after `stepResult` runs. Nodes start only when their forward predecessors finish and edges reach them. **Early termination (#1537, #1538, #1546, #1570, #1571):** When a node completes **or fails**, the run ends immediately with status `done`, sets `run.earlyEnd` to the condition name, and does not advance to successors, take a success-path `loop`, or burn `onFail` recovery attempts. The two markers that report the task itself end it only on a structured signal (#1546): `needs-human` and `already-claimed` must be a declared OUTPUT whose value **equals** the marker, or a whole reply line that is exactly `EARLY-END ` in any case. A step that quotes an issue title, negates the label or reports it absent keeps running. `tip-unchanged` (#1570) and `open-pr` (#1571) accept that same structured signal — in a declared OUTPUT the value counts as a whole word, so a brief that names `data-open-project` is not `open-pr` (#1866) — and also honor their prose fallbacks (`tip unchanged` / `unchanged tip`, `open PR already` / `already has an open PR` / `has an open PR` / `found an open PR`), so a Bot that forgets the structured marker cannot soft-lock Claim↔Verify on the same tip. See `checkEarlyEnd` in Key files. Factory prompt guidance lives in `EARLY_END_GUIDANCE` (`plugins/workflow/src/template.js`) for Settings graphs that wire Triage / Claim / Verify: Verify must escalate once on an unchanged tip, not re-run the full suite. There is no scripted or seeded run path: `workflow/state` exposes only `live === true` runs — the running ones, plus the last run when it is still `live` and ended `failed` — a failed sibling stays on the stage beside whatever is running now, with `run.failure` (`{ code, at, nodeName?, text? }`) naming what ended it, so the room does not have to open Runs to learn that a run failed (#1493, #1494). The failed sibling is left out when a running run carries the same task id: that is a retry, and the live run keeps the row (#1507). History entries carry the run `id` and the same `failure`, so a Runs row shows when the run ended and why, and a row for a run already on the stage is not listed twice. A run does not create a schedule. `scheduleLabel` is display text. When the host can create Bots, starting a live run (`assign`, `run_workflow`, `ingest`) spawns one ephemeral Bot per node from that node's prompt, role, model and tools, sends it the step from the Main Bot, and removes every instance when the run finishes, fails for good, or is reset. A `failOnce` retry keeps them. They are hidden and left out of the sidebar. Loading the plugin does not spawn Bots for the default workflows. Plugin unload (`dispose`) and the load-time `reap` both end a live run still marked `running`: in-flight nodes are failed, the run is archived as `failed`, and any ephemeral Bot ids are released. A **read-only** host — a second window on the same `DSH_HOME`, the reader `home-lock` describes — does neither: it never ran those runs, so it cannot tell which of them a dead host left behind, and it must not end them, release their step Bots or write its older copy over the writer's store; both calls return without touching the record and the writer's own `reap` decides (#2673). **Taking the lock over is a state change (#2704):** the first call that finds the host writable after this window started read-only — a read, `reap`, `dispose` or any write — re-reads `workflows.json` once before it changes anything, because the copy it loaded predates what the dead window saved, and then runs the same load-time `reap` once on that adopted store. That reap ends the dead window's `running` run as `host-ended` (or heals a `live:true` run whose Bot map is already gone, #1414) and releases its step Bots; `lane.queue` is never touched, so a card that was merely `queued` keeps its place and starts when the lane drains. Only the first such call re-reads — a writer that later loses the lock is still refused, exactly as before. A run already written as `running` with no ephemeral map (an older unload) is healed the same way on the next load (#1414). Loading is also the one moment a run the host left behind is noticed when its ephemeral map is still present: `reap` releases those instances and records the run as `failed`. Nothing resumes it, and that ending drains the lane's queue like any other terminal transition, so a card parked behind the dead run starts on load instead of waiting for the next assign (#2752). A run that already ended keeps its own status (#1388). `workflow/reset` stopping one live run ends it the same way before its Bots are released: nodes still `running` become `failed`, so the strip cannot keep painting a run that is over (#1424). A graph edit that drops a node that is still running ends that run the way Stop does: the node is failed, the run is archived `failed`, its node Bots are released, and the queue drains (#1549); an id whose release failed stays named on that archived run, and the next load's `reap` retries it, instead of the edit forgetting it (the #1616 contract). Every wait is bounded (#1530). A dispatch that does not land is not marked handed: the chat names the code and the attempt, and it is retried after a short backoff at most twice, never twice inside one hand-off, so a 429 is not hammered. When it still does not land, the step and the run fail with the reason written into the chat. Each running live step also holds a deadline — its workflow's `stepTimeoutMinutes`, `DEFAULT_STEP_TIMEOUT_MINUTES` (45 minutes) unless the record sets one, an integer from 1 to 120 given at create, through `define_workflow`, or through `workflow/step-timeout` (armed even when the host cannot spawn ephemeral Bots; #1530, #1580); when it expires the node and the run fail as `failed`, the run's ephemeral Bots are released, the chat and `run.failure` say the step's deadline was reached (`step deadline reached (45 min)`, the number its lane set), and `warn` names it once; the line never reads as a reply that did not arrive, because a step still working is killed by the same timer (#1868). The deadline is cleared as soon as the step moves, and by Pause, Reset, delete, `reap`, `dispose` and a Stop that released every Bot; a run the owner paused holds none, and Resume arms it again from that moment. A timer never outlives the run that started it. A reply that matches no running step — its run ended, or the node already moved — is reported through `warn` once per Bot and run instead of being dropped silently. A reply fails that node on a structured signal only: the host's failure notice carries `failure: true`, which the middleware hands `stepResult` as `ok: false` (a caller-set `ok: false` counts too), so an answer that quotes `could not answer your message` or `model call failed` while auditing it advances the step (#2677). An old host without the marker falls back to the notice shapes at the start of the text only (` could not answer your message: …`, ` was stopped before it could answer your message.`, and the bare `could not answer your message` / `The model call failed.` an old host wrote), never a free substring, so an ordinary answer that merely ends in the model-failure wording keeps advancing the step (#2741). A stopped turn is a failed step, with the stop notice as its reason, instead of finishing as done and handing that notice to the next node (#2741). A 429 or rate-limit mention in any other reply does not fail a step. Stop and Reset (`workflow/reset`) follow the same order as `dispose`: they release the run's Bots before the record forgets their ids, and an id whose release failed stays named on the still-live run, so the next Stop, Reset, dispose or load-time `reap` retries it (#1476). A run left that way is marked `paused` and `releasePending` and shows as Paused: it hands off no further node, `resume` is refused with an error, and Stop again is the retry. It also keeps the deadline of the node it was on — the one paused state that holds one — and a graph save re-syncs timers without taking it away (a save that cleared it left the run holding its slot with nothing left to free it); the deadline releases again there, ends the run as `paused-expired` and frees the slot, re-arming itself while a Bot still will not go (#2453, P-560). A whole-workflow Reset that could not release every Bot freezes every run it did not reset, because each of them has lost the ids whose release did go. The markers go away when the run ends: Stop again, `dispose`, `reap`, or its own completion. 4. Each workflow keeps a FIFO queue and up to `maxConcurrent` live runs (default 2, an integer from 1 to 8 on the record, via `workflow/concurrency`, or in Settings → Workflow graphs). A task that does not fit is enqueued. When a run finishes, every workflow with a free slot is drained, oldest enqueue first. A new assign on a workflow that already has a queue waits behind it. A task does not replace a running run or release that run's Bots. Migrating an old store keeps only runs that were still `running` with ephemeral Bot ids; other legacy scripted rows are dropped from active state (finished tasks may remain in lane history). History records a finished or failed live run. Lowering the cap does not stop a run that has already started. Assigning `{ botId }` claims the card for that local Bot and does not enqueue. A remote Bot is refused. `activeCount` is `runningOf(lane)` — live runs with `live === true` and `status === 'running'`. The stage aggregate chip and the Runs tab (运行记录) must agree: every such run appears as its own running row and progress card with its own `status` (never a hardcoded Running), the chip count does not exceed that list, and a failed sibling appears with its time and reason. On the Runs list, the clock stays in a non-shrinking column with a gap before the status chip, and a Failed row paints the Failed chip once — a generic Failed with no host detail does not also draw `wf-hist-reason` (#1618). 5. A node declares up to eight inputs and eight outputs. A required input is an output of the same name on an ancestor, or `task`, `title`, or `brief` on a root. A start with no provider is refused, and Bots spawned for that attempt are released. On a Bot-backed run a successor stays queued until its required inputs are present. If every forward predecessor is done, failed or skipped and an input is still missing, that node fails and the run stops. The dispatch text carries `Input : `. It also lists the OUTPUT lines the step owes — its declared ports plus every output its outgoing edges read, whether a condition's `when` or a loop's `until` (`edgeOutputs` in `src/graph.js`) — spelled `OUTPUT : ` when an edge compares that output against a value — so a node that declares no outputs is still told which line its own gate reads (#2669, #2685). The Bot reports `OUTPUT : `; a single declared output may be the reply body. A declared output a gate reads is required (§3): when a `when`/`else` or `until` edge reads it and the step's reply does not produce it, the step fails with `failure.text` `Missing OUTPUT ` instead of settling, so the gate never reads silence as "not this branch" and the run cannot close `done` on it; a delivered value that does not equal `eq` still completes the step and skips the untaken branch (#1773). One exception keeps the work a step already did (#2583, #2658): when `state` is the only gate-read output missing and the step's own reply shows its result — a pull request link, `pull/`, a line saying it opened PR #n, a `Claimed-by:` / `Claimed #n` line, or its own declared OUTPUT names the delivery (`pr`/`pull` whose value is only a pull number — a positive integer, optional leading `#`, optional trailing parenthetical such as `2657 (verified)` — or `merged`/`merge-commit` carrying a 40-character commit sha; any other output name counts for nothing) — the step stands as `done`, the run takes the node's first declared `state` branch (on the fast line `state: ready → claim`, so the pull request reaches gate/enqueue instead of the `else` route the step never chose), and the run record carries `outputMissing: true` and `producedPull: ` when a pull request was named; every other missing verdict still fails, and a step whose reply shows no such result still fails the same way. `stepArtifacts` reads that evidence and `firstBranchValue` names the branch, both in `src/graph.js`; the engine has no GitHub client, so the reply is the only evidence it can read. Nodes start in edge order. 6. Each node is a real ephemeral Bot for that run, then it is removed. A permanent sidebar Bot (`botId`) is optional and is not required for the step to run. **File and shell rights are the same as a normal sidebar Bot's:** every node Bot gets the `danger-full-access` preset, and `EPHEMERAL_DENIED_TOOLS` still refuses the team-admin tools at the guard and approval layers (#1466, 29 names). **`node.tools` selects connectors only:** `spawn` passes the node's cleaned list to `fb.bot.create`, the host records it as `stepTools`, and `connector-access.js` allows `mcp__github__*` for `github` and `mcp__composio__*` for `composio` — a connector the node did not name is refused, and a node that names none reaches none. The list is also stored in `fields.tools` for the UI. A hidden run Bot cannot show an approval card, so the approval seam answers the same way the guard does. The host stores this on the run Bot as `stepTools` and `permission`. diff --git a/plugins/workflow/src/service.js b/plugins/workflow/src/service.js index 4bc1ac77b..f241ba744 100644 --- a/plugins/workflow/src/service.js +++ b/plugins/workflow/src/service.js @@ -2255,12 +2255,13 @@ export function createWorkflowService({ if (!writable()) return Promise.resolve() // #2704: the call that noticed the takeover already started the same reaper a load // runs; hand that one back instead of releasing the dead window's Bots twice. - if (takingOver !== null) { - const pending = takingOver - takingOver = null - return pending - } - return reapRuns() + const pending = takingOver !== null ? takingOver : reapRuns() + takingOver = null + // #2752: a run this reap ended is a terminal transition like a step's own ending, so + // the queue moves on it. With the drain on the finish paths only, the card behind a + // `host-ended` run stays parked while the lane reports a free slot and nothing + // running, and the next assign is what finally starts it. + return pending.then(() => drainAll()) }, dispose() { for (const key of [...timers.keys()]) clearTimerAt(key) diff --git a/plugins/workflow/test/queued-card-starts-after-failed-run.test.js b/plugins/workflow/test/queued-card-starts-after-failed-run.test.js new file mode 100644 index 000000000..0318eab48 --- /dev/null +++ b/plugins/workflow/test/queued-card-starts-after-failed-run.test.js @@ -0,0 +1,64 @@ +// #2752: a card queued behind a run that ends **failed** must start, exactly like one +// queued behind a run that ends `done`. The queue is filled while the line is at its cap, +// so the ending is what has to move it — waiting for the next assign leaves the card +// parked with `queueDepth > 0` and `activeCount 0` while the line looks idle. +// +// The ending under test is the reaper's: a run whose host died comes back from the store +// still `running`, `reap()` ends it `host-ended`, and that is a terminal transition like +// any other. A drain that lives only on the happy path never sees it. +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { createWorkflowService } from '../src/service.js' +import { DELIVERY_ID } from '../src/template.js' + +const AT = 1_700_000_000_000 + +function bench(dir, seed) { + const state = { seed, spawned: [] } + const svc = createWorkflowService({ + dir, + now: () => AT, + bots: () => [{ id: 'main', name: 'Chief', isMain: true, remote: false }], + spawn: async () => { + state.seed += 1 + const id = `eph-${state.seed}` + state.spawned.push(id) + return id + }, + release: () => {}, + dispatch: async () => ({ ok: true }), + // No deadlines here: the ending this test needs is the one the load produces. + setTimer: () => 1, + clearTimer: () => {}, + }) + return { svc, state } +} + +const row = svc => svc.state().workflows.find(item => item.id === DELIVERY_ID) +const running = svc => row(svc).runs.filter(run => run.status === 'running').map(run => run.task?.id) +const queueDepth = svc => row(svc).queueDepth + +test('a card queued behind a run the host ended failed starts after the reap', async () => { + const dir = mkdtempSync(join(tmpdir(), 'wf-2752-')) + try { + const first = bench(dir, 0) + first.svc.setConcurrency({ workflowId: DELIVERY_ID, maxConcurrent: 1 }) + await first.svc.ingest({ id: '#A', title: 'First card', status: 'open', workflowId: DELIVERY_ID }) + await first.svc.ingest({ id: '#B', title: 'Second card', status: 'open', workflowId: DELIVERY_ID }) + assert.deepEqual(running(first.svc), ['#A'], 'the first card did not start') + assert.equal(queueDepth(first.svc), 1, 'the second card was not parked behind the cap') + + // The host that ran #A is gone: its Bots went with it and the store still says + // `running`. The next host loads that store and reaps the run as `host-ended`. + const second = bench(dir, 100) + await second.svc.reap() + + assert.deepEqual(running(second.svc), ['#B'], 'the parked card did not start after the failed run ended') + assert.equal(queueDepth(second.svc), 0, 'the queue kept the card while the line had a free slot') + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) From 985d7d2395c46850fb248e6d36ea095929ceb7ad Mon Sep 17 00:00:00 2001 From: FlyBot Dev-3 Date: Tue, 10 Nov 2026 01:02:25 +0000 Subject: [PATCH 2/2] fix(workflow): run the reap's drain on the serial tail The load fires the reap without awaiting it, so its drain and a concurrent assign both read `runningOf` before either `beginRun` lands: each saw a free slot and started a card, leaving two runs on a lane whose cap is one. The drain now joins the same `hostSerial` tail every assign takes, and the race has its own test: a load-time reap racing an assign at cap 1 starts one card, not two. Fixes #2752 --- docs/subsystems/workflow.md | 2 +- plugins/workflow/src/service.js | 6 ++++- ...ueued-card-starts-after-failed-run.test.js | 27 +++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/docs/subsystems/workflow.md b/docs/subsystems/workflow.md index 897712b1f..cfe134407 100644 --- a/docs/subsystems/workflow.md +++ b/docs/subsystems/workflow.md @@ -59,7 +59,7 @@ Everything in `plugins/workflow/`: the graph rules, the run store, the matcher, 1. Friends' Bots are not nodes. A `remote` Bot is refused by create, define and the matcher. 2. The canvas and the run share one graph: nodes, edges and positions. A drag commits `workflow/graph`, but only while **Edit** is on — a factory preset is copied first (#1378). A wire or a reconnect that would list a pair the graph already carries commits nothing new, because `normalizeGraph` refuses a graph that lists one pair twice and then saves none of it: unguarded, the plane would show no edge, no change and only a save error (#2163). Status highlighting reads that same graph. Replacing edges does not recompute who is already running. The Settings canvas paints that graph on the same 960px design plane, scaled to the width the settings page gives it, so the canvas is not a second scroll container inside the page's own scroll; its pointer deltas are divided by the scale, and its wires keep a stronger stroke than a plain divider so an edge can be followed at that size (#1483). While another dsh holds the Bot team the host is read-only (`roster.readOnly`): the page still reads through `workflow/state`, keeps its controls disabled, and offers no **Edit**, **Add link** or wire port, so it cannot take a change that core would refuse with `bot/read-only` and then drop (#2187). The same window draws the sidebar's workflow list without **New**, the row's **Rename**/**Delete** or **Hand a task to a Workflow**: the list is read-only too, and an `roster.readOnly` that is not a string, or holds only whitespace, counts as writable — trimmed the way `core/src/client/workflows.js:570` trims it (#2200). The Stage a row opens carries the same lock: it prints the host's sentence under `role="status"` and draws no **Hand a task to a Workflow**, no **Re-match**, no **Pause**/**Resume**/**Stop**, no **Edit**/drag palette and no **Reset**, while the row click, **Progress**, **Flow** and viewing a run still work; a writable roster draws every control exactly as before (#2213). Mounting the list in a read-only window still reads `projects` so the Project filter fills, but it sends no `workflow/ingest` for the open cards: ingest is a claim/match write the host refuses, so a reader opening the list writes nothing; a writable window still ingests every open card (#2222). The read-only sentence can also land after the list has mounted — a cold window starts on the empty roster, `ready: false` and no `readOnly` — so the ingest step asks the value the latest render saw rather than the one the mount saw, and it skips the board read and stops between two cards once the window has turned read-only. The Settings page draws no read-only sentence of its own: the host's Settings header already prints one for every page it shows (`core/src/client/settings.js` `bt-read-only`, `role="status"`, `hostText(roster.readOnly)`), and a second copy inside the page said the same thing twice (#2202). -3. **A live run advances only when its ephemeral Bot replies, following the graph's edges in order.** That reply advances the run and may appear on the workflow stage log; it is not delivered into a persistent sidebar Bot conversation (for example Chief). The `workflow-step` send middleware denies those replies after `stepResult` runs. Nodes start only when their forward predecessors finish and edges reach them. **Early termination (#1537, #1538, #1546, #1570, #1571):** When a node completes **or fails**, the run ends immediately with status `done`, sets `run.earlyEnd` to the condition name, and does not advance to successors, take a success-path `loop`, or burn `onFail` recovery attempts. The two markers that report the task itself end it only on a structured signal (#1546): `needs-human` and `already-claimed` must be a declared OUTPUT whose value **equals** the marker, or a whole reply line that is exactly `EARLY-END ` in any case. A step that quotes an issue title, negates the label or reports it absent keeps running. `tip-unchanged` (#1570) and `open-pr` (#1571) accept that same structured signal — in a declared OUTPUT the value counts as a whole word, so a brief that names `data-open-project` is not `open-pr` (#1866) — and also honor their prose fallbacks (`tip unchanged` / `unchanged tip`, `open PR already` / `already has an open PR` / `has an open PR` / `found an open PR`), so a Bot that forgets the structured marker cannot soft-lock Claim↔Verify on the same tip. See `checkEarlyEnd` in Key files. Factory prompt guidance lives in `EARLY_END_GUIDANCE` (`plugins/workflow/src/template.js`) for Settings graphs that wire Triage / Claim / Verify: Verify must escalate once on an unchanged tip, not re-run the full suite. There is no scripted or seeded run path: `workflow/state` exposes only `live === true` runs — the running ones, plus the last run when it is still `live` and ended `failed` — a failed sibling stays on the stage beside whatever is running now, with `run.failure` (`{ code, at, nodeName?, text? }`) naming what ended it, so the room does not have to open Runs to learn that a run failed (#1493, #1494). The failed sibling is left out when a running run carries the same task id: that is a retry, and the live run keeps the row (#1507). History entries carry the run `id` and the same `failure`, so a Runs row shows when the run ended and why, and a row for a run already on the stage is not listed twice. A run does not create a schedule. `scheduleLabel` is display text. When the host can create Bots, starting a live run (`assign`, `run_workflow`, `ingest`) spawns one ephemeral Bot per node from that node's prompt, role, model and tools, sends it the step from the Main Bot, and removes every instance when the run finishes, fails for good, or is reset. A `failOnce` retry keeps them. They are hidden and left out of the sidebar. Loading the plugin does not spawn Bots for the default workflows. Plugin unload (`dispose`) and the load-time `reap` both end a live run still marked `running`: in-flight nodes are failed, the run is archived as `failed`, and any ephemeral Bot ids are released. A **read-only** host — a second window on the same `DSH_HOME`, the reader `home-lock` describes — does neither: it never ran those runs, so it cannot tell which of them a dead host left behind, and it must not end them, release their step Bots or write its older copy over the writer's store; both calls return without touching the record and the writer's own `reap` decides (#2673). **Taking the lock over is a state change (#2704):** the first call that finds the host writable after this window started read-only — a read, `reap`, `dispose` or any write — re-reads `workflows.json` once before it changes anything, because the copy it loaded predates what the dead window saved, and then runs the same load-time `reap` once on that adopted store. That reap ends the dead window's `running` run as `host-ended` (or heals a `live:true` run whose Bot map is already gone, #1414) and releases its step Bots; `lane.queue` is never touched, so a card that was merely `queued` keeps its place and starts when the lane drains. Only the first such call re-reads — a writer that later loses the lock is still refused, exactly as before. A run already written as `running` with no ephemeral map (an older unload) is healed the same way on the next load (#1414). Loading is also the one moment a run the host left behind is noticed when its ephemeral map is still present: `reap` releases those instances and records the run as `failed`. Nothing resumes it, and that ending drains the lane's queue like any other terminal transition, so a card parked behind the dead run starts on load instead of waiting for the next assign (#2752). A run that already ended keeps its own status (#1388). `workflow/reset` stopping one live run ends it the same way before its Bots are released: nodes still `running` become `failed`, so the strip cannot keep painting a run that is over (#1424). A graph edit that drops a node that is still running ends that run the way Stop does: the node is failed, the run is archived `failed`, its node Bots are released, and the queue drains (#1549); an id whose release failed stays named on that archived run, and the next load's `reap` retries it, instead of the edit forgetting it (the #1616 contract). Every wait is bounded (#1530). A dispatch that does not land is not marked handed: the chat names the code and the attempt, and it is retried after a short backoff at most twice, never twice inside one hand-off, so a 429 is not hammered. When it still does not land, the step and the run fail with the reason written into the chat. Each running live step also holds a deadline — its workflow's `stepTimeoutMinutes`, `DEFAULT_STEP_TIMEOUT_MINUTES` (45 minutes) unless the record sets one, an integer from 1 to 120 given at create, through `define_workflow`, or through `workflow/step-timeout` (armed even when the host cannot spawn ephemeral Bots; #1530, #1580); when it expires the node and the run fail as `failed`, the run's ephemeral Bots are released, the chat and `run.failure` say the step's deadline was reached (`step deadline reached (45 min)`, the number its lane set), and `warn` names it once; the line never reads as a reply that did not arrive, because a step still working is killed by the same timer (#1868). The deadline is cleared as soon as the step moves, and by Pause, Reset, delete, `reap`, `dispose` and a Stop that released every Bot; a run the owner paused holds none, and Resume arms it again from that moment. A timer never outlives the run that started it. A reply that matches no running step — its run ended, or the node already moved — is reported through `warn` once per Bot and run instead of being dropped silently. A reply fails that node on a structured signal only: the host's failure notice carries `failure: true`, which the middleware hands `stepResult` as `ok: false` (a caller-set `ok: false` counts too), so an answer that quotes `could not answer your message` or `model call failed` while auditing it advances the step (#2677). An old host without the marker falls back to the notice shapes at the start of the text only (` could not answer your message: …`, ` was stopped before it could answer your message.`, and the bare `could not answer your message` / `The model call failed.` an old host wrote), never a free substring, so an ordinary answer that merely ends in the model-failure wording keeps advancing the step (#2741). A stopped turn is a failed step, with the stop notice as its reason, instead of finishing as done and handing that notice to the next node (#2741). A 429 or rate-limit mention in any other reply does not fail a step. Stop and Reset (`workflow/reset`) follow the same order as `dispose`: they release the run's Bots before the record forgets their ids, and an id whose release failed stays named on the still-live run, so the next Stop, Reset, dispose or load-time `reap` retries it (#1476). A run left that way is marked `paused` and `releasePending` and shows as Paused: it hands off no further node, `resume` is refused with an error, and Stop again is the retry. It also keeps the deadline of the node it was on — the one paused state that holds one — and a graph save re-syncs timers without taking it away (a save that cleared it left the run holding its slot with nothing left to free it); the deadline releases again there, ends the run as `paused-expired` and frees the slot, re-arming itself while a Bot still will not go (#2453, P-560). A whole-workflow Reset that could not release every Bot freezes every run it did not reset, because each of them has lost the ids whose release did go. The markers go away when the run ends: Stop again, `dispose`, `reap`, or its own completion. +3. **A live run advances only when its ephemeral Bot replies, following the graph's edges in order.** That reply advances the run and may appear on the workflow stage log; it is not delivered into a persistent sidebar Bot conversation (for example Chief). The `workflow-step` send middleware denies those replies after `stepResult` runs. Nodes start only when their forward predecessors finish and edges reach them. **Early termination (#1537, #1538, #1546, #1570, #1571):** When a node completes **or fails**, the run ends immediately with status `done`, sets `run.earlyEnd` to the condition name, and does not advance to successors, take a success-path `loop`, or burn `onFail` recovery attempts. The two markers that report the task itself end it only on a structured signal (#1546): `needs-human` and `already-claimed` must be a declared OUTPUT whose value **equals** the marker, or a whole reply line that is exactly `EARLY-END ` in any case. A step that quotes an issue title, negates the label or reports it absent keeps running. `tip-unchanged` (#1570) and `open-pr` (#1571) accept that same structured signal — in a declared OUTPUT the value counts as a whole word, so a brief that names `data-open-project` is not `open-pr` (#1866) — and also honor their prose fallbacks (`tip unchanged` / `unchanged tip`, `open PR already` / `already has an open PR` / `has an open PR` / `found an open PR`), so a Bot that forgets the structured marker cannot soft-lock Claim↔Verify on the same tip. See `checkEarlyEnd` in Key files. Factory prompt guidance lives in `EARLY_END_GUIDANCE` (`plugins/workflow/src/template.js`) for Settings graphs that wire Triage / Claim / Verify: Verify must escalate once on an unchanged tip, not re-run the full suite. There is no scripted or seeded run path: `workflow/state` exposes only `live === true` runs — the running ones, plus the last run when it is still `live` and ended `failed` — a failed sibling stays on the stage beside whatever is running now, with `run.failure` (`{ code, at, nodeName?, text? }`) naming what ended it, so the room does not have to open Runs to learn that a run failed (#1493, #1494). The failed sibling is left out when a running run carries the same task id: that is a retry, and the live run keeps the row (#1507). History entries carry the run `id` and the same `failure`, so a Runs row shows when the run ended and why, and a row for a run already on the stage is not listed twice. A run does not create a schedule. `scheduleLabel` is display text. When the host can create Bots, starting a live run (`assign`, `run_workflow`, `ingest`) spawns one ephemeral Bot per node from that node's prompt, role, model and tools, sends it the step from the Main Bot, and removes every instance when the run finishes, fails for good, or is reset. A `failOnce` retry keeps them. They are hidden and left out of the sidebar. Loading the plugin does not spawn Bots for the default workflows. Plugin unload (`dispose`) and the load-time `reap` both end a live run still marked `running`: in-flight nodes are failed, the run is archived as `failed`, and any ephemeral Bot ids are released. A **read-only** host — a second window on the same `DSH_HOME`, the reader `home-lock` describes — does neither: it never ran those runs, so it cannot tell which of them a dead host left behind, and it must not end them, release their step Bots or write its older copy over the writer's store; both calls return without touching the record and the writer's own `reap` decides (#2673). **Taking the lock over is a state change (#2704):** the first call that finds the host writable after this window started read-only — a read, `reap`, `dispose` or any write — re-reads `workflows.json` once before it changes anything, because the copy it loaded predates what the dead window saved, and then runs the same load-time `reap` once on that adopted store. That reap ends the dead window's `running` run as `host-ended` (or heals a `live:true` run whose Bot map is already gone, #1414) and releases its step Bots; `lane.queue` is never touched, so a card that was merely `queued` keeps its place and starts when the lane drains. Only the first such call re-reads — a writer that later loses the lock is still refused, exactly as before. A run already written as `running` with no ephemeral map (an older unload) is healed the same way on the next load (#1414). Loading is also the one moment a run the host left behind is noticed when its ephemeral map is still present: `reap` releases those instances and records the run as `failed`. Nothing resumes it, and that ending drains the lane's queue like any other terminal transition, so a card parked behind the dead run starts on load instead of waiting for the next assign (#2752); that drain joins the serial tail the assigns use, because the load does not await the reap and a drain outside it would start a second card beside the assign at the lane's cap (#2757). A run that already ended keeps its own status (#1388). `workflow/reset` stopping one live run ends it the same way before its Bots are released: nodes still `running` become `failed`, so the strip cannot keep painting a run that is over (#1424). A graph edit that drops a node that is still running ends that run the way Stop does: the node is failed, the run is archived `failed`, its node Bots are released, and the queue drains (#1549); an id whose release failed stays named on that archived run, and the next load's `reap` retries it, instead of the edit forgetting it (the #1616 contract). Every wait is bounded (#1530). A dispatch that does not land is not marked handed: the chat names the code and the attempt, and it is retried after a short backoff at most twice, never twice inside one hand-off, so a 429 is not hammered. When it still does not land, the step and the run fail with the reason written into the chat. Each running live step also holds a deadline — its workflow's `stepTimeoutMinutes`, `DEFAULT_STEP_TIMEOUT_MINUTES` (45 minutes) unless the record sets one, an integer from 1 to 120 given at create, through `define_workflow`, or through `workflow/step-timeout` (armed even when the host cannot spawn ephemeral Bots; #1530, #1580); when it expires the node and the run fail as `failed`, the run's ephemeral Bots are released, the chat and `run.failure` say the step's deadline was reached (`step deadline reached (45 min)`, the number its lane set), and `warn` names it once; the line never reads as a reply that did not arrive, because a step still working is killed by the same timer (#1868). The deadline is cleared as soon as the step moves, and by Pause, Reset, delete, `reap`, `dispose` and a Stop that released every Bot; a run the owner paused holds none, and Resume arms it again from that moment. A timer never outlives the run that started it. A reply that matches no running step — its run ended, or the node already moved — is reported through `warn` once per Bot and run instead of being dropped silently. A reply fails that node on a structured signal only: the host's failure notice carries `failure: true`, which the middleware hands `stepResult` as `ok: false` (a caller-set `ok: false` counts too), so an answer that quotes `could not answer your message` or `model call failed` while auditing it advances the step (#2677). An old host without the marker falls back to the notice shapes at the start of the text only (` could not answer your message: …`, ` was stopped before it could answer your message.`, and the bare `could not answer your message` / `The model call failed.` an old host wrote), never a free substring, so an ordinary answer that merely ends in the model-failure wording keeps advancing the step (#2741). A stopped turn is a failed step, with the stop notice as its reason, instead of finishing as done and handing that notice to the next node (#2741). A 429 or rate-limit mention in any other reply does not fail a step. Stop and Reset (`workflow/reset`) follow the same order as `dispose`: they release the run's Bots before the record forgets their ids, and an id whose release failed stays named on the still-live run, so the next Stop, Reset, dispose or load-time `reap` retries it (#1476). A run left that way is marked `paused` and `releasePending` and shows as Paused: it hands off no further node, `resume` is refused with an error, and Stop again is the retry. It also keeps the deadline of the node it was on — the one paused state that holds one — and a graph save re-syncs timers without taking it away (a save that cleared it left the run holding its slot with nothing left to free it); the deadline releases again there, ends the run as `paused-expired` and frees the slot, re-arming itself while a Bot still will not go (#2453, P-560). A whole-workflow Reset that could not release every Bot freezes every run it did not reset, because each of them has lost the ids whose release did go. The markers go away when the run ends: Stop again, `dispose`, `reap`, or its own completion. 4. Each workflow keeps a FIFO queue and up to `maxConcurrent` live runs (default 2, an integer from 1 to 8 on the record, via `workflow/concurrency`, or in Settings → Workflow graphs). A task that does not fit is enqueued. When a run finishes, every workflow with a free slot is drained, oldest enqueue first. A new assign on a workflow that already has a queue waits behind it. A task does not replace a running run or release that run's Bots. Migrating an old store keeps only runs that were still `running` with ephemeral Bot ids; other legacy scripted rows are dropped from active state (finished tasks may remain in lane history). History records a finished or failed live run. Lowering the cap does not stop a run that has already started. Assigning `{ botId }` claims the card for that local Bot and does not enqueue. A remote Bot is refused. `activeCount` is `runningOf(lane)` — live runs with `live === true` and `status === 'running'`. The stage aggregate chip and the Runs tab (运行记录) must agree: every such run appears as its own running row and progress card with its own `status` (never a hardcoded Running), the chip count does not exceed that list, and a failed sibling appears with its time and reason. On the Runs list, the clock stays in a non-shrinking column with a gap before the status chip, and a Failed row paints the Failed chip once — a generic Failed with no host detail does not also draw `wf-hist-reason` (#1618). 5. A node declares up to eight inputs and eight outputs. A required input is an output of the same name on an ancestor, or `task`, `title`, or `brief` on a root. A start with no provider is refused, and Bots spawned for that attempt are released. On a Bot-backed run a successor stays queued until its required inputs are present. If every forward predecessor is done, failed or skipped and an input is still missing, that node fails and the run stops. The dispatch text carries `Input : `. It also lists the OUTPUT lines the step owes — its declared ports plus every output its outgoing edges read, whether a condition's `when` or a loop's `until` (`edgeOutputs` in `src/graph.js`) — spelled `OUTPUT : ` when an edge compares that output against a value — so a node that declares no outputs is still told which line its own gate reads (#2669, #2685). The Bot reports `OUTPUT : `; a single declared output may be the reply body. A declared output a gate reads is required (§3): when a `when`/`else` or `until` edge reads it and the step's reply does not produce it, the step fails with `failure.text` `Missing OUTPUT ` instead of settling, so the gate never reads silence as "not this branch" and the run cannot close `done` on it; a delivered value that does not equal `eq` still completes the step and skips the untaken branch (#1773). One exception keeps the work a step already did (#2583, #2658): when `state` is the only gate-read output missing and the step's own reply shows its result — a pull request link, `pull/`, a line saying it opened PR #n, a `Claimed-by:` / `Claimed #n` line, or its own declared OUTPUT names the delivery (`pr`/`pull` whose value is only a pull number — a positive integer, optional leading `#`, optional trailing parenthetical such as `2657 (verified)` — or `merged`/`merge-commit` carrying a 40-character commit sha; any other output name counts for nothing) — the step stands as `done`, the run takes the node's first declared `state` branch (on the fast line `state: ready → claim`, so the pull request reaches gate/enqueue instead of the `else` route the step never chose), and the run record carries `outputMissing: true` and `producedPull: ` when a pull request was named; every other missing verdict still fails, and a step whose reply shows no such result still fails the same way. `stepArtifacts` reads that evidence and `firstBranchValue` names the branch, both in `src/graph.js`; the engine has no GitHub client, so the reply is the only evidence it can read. Nodes start in edge order. 6. Each node is a real ephemeral Bot for that run, then it is removed. A permanent sidebar Bot (`botId`) is optional and is not required for the step to run. **File and shell rights are the same as a normal sidebar Bot's:** every node Bot gets the `danger-full-access` preset, and `EPHEMERAL_DENIED_TOOLS` still refuses the team-admin tools at the guard and approval layers (#1466, 29 names). **`node.tools` selects connectors only:** `spawn` passes the node's cleaned list to `fb.bot.create`, the host records it as `stepTools`, and `connector-access.js` allows `mcp__github__*` for `github` and `mcp__composio__*` for `composio` — a connector the node did not name is refused, and a node that names none reaches none. The list is also stored in `fields.tools` for the UI. A hidden run Bot cannot show an approval card, so the approval seam answers the same way the guard does. The host stores this on the run Bot as `stepTools` and `permission`. diff --git a/plugins/workflow/src/service.js b/plugins/workflow/src/service.js index f241ba744..aad82fe7d 100644 --- a/plugins/workflow/src/service.js +++ b/plugins/workflow/src/service.js @@ -2261,7 +2261,11 @@ export function createWorkflowService({ // the queue moves on it. With the drain on the finish paths only, the card behind a // `host-ended` run stays parked while the lane reports a free slot and nothing // running, and the next assign is what finally starts it. - return pending.then(() => drainAll()) + // #2757: the caller does not await this reap — a load fires it and moves on — so the + // drain joins the serial tail the assigns use. Outside it, this drain and a concurrent + // `assign` both read `runningOf` before either `beginRun` lands, each sees a free slot + // and starts a card: two runs at cap 1, the second one over the lane's ceiling. + return pending.then(() => hostSerial(() => drainAll())) }, dispose() { for (const key of [...timers.keys()]) clearTimerAt(key) diff --git a/plugins/workflow/test/queued-card-starts-after-failed-run.test.js b/plugins/workflow/test/queued-card-starts-after-failed-run.test.js index 0318eab48..c78cf3ebc 100644 --- a/plugins/workflow/test/queued-card-starts-after-failed-run.test.js +++ b/plugins/workflow/test/queued-card-starts-after-failed-run.test.js @@ -62,3 +62,30 @@ test('a card queued behind a run the host ended failed starts after the reap', a rmSync(dir, { recursive: true, force: true }) } }) + +// The reaper a load fires is not awaited (`plugins/workflow/index.js`), so it can end a run +// while an `assign` is already in flight. Both starts read `runningOf` before either +// `beginRun` lands, so a drain outside the serial tail lets each of them see the same free +// slot and start a card: a lane at cap 1 ends up with two runs and no queue. +test('a load-time reap racing an assign never starts more than the lane cap', async () => { + const dir = mkdtempSync(join(tmpdir(), 'wf-2752-race-')) + try { + const first = bench(dir, 0) + first.svc.setConcurrency({ workflowId: DELIVERY_ID, maxConcurrent: 1 }) + await first.svc.ingest({ id: '#A', title: 'First card', status: 'open', workflowId: DELIVERY_ID }) + await first.svc.ingest({ id: '#B', title: 'Second card', status: 'open', workflowId: DELIVERY_ID }) + assert.deepEqual(running(first.svc), ['#A']) + assert.equal(queueDepth(first.svc), 1) + + const second = bench(dir, 100) + // What loading does, and what an `assign` from the board does at the same moment. + const reaped = second.svc.reap() + const assigned = second.svc.assign({ workflowId: DELIVERY_ID, taskId: '#C', title: 'Third card' }) + await Promise.all([reaped, assigned]) + + assert.equal(running(second.svc).length, 1, 'the lane started two cards at cap 1') + assert.equal(running(second.svc).length + queueDepth(second.svc), 2, 'a card left the lane without a run') + } finally { + rmSync(dir, { recursive: true, force: true }) + } +})