@jive-sh/workflow-platform 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jive-sh/workflow-platform",
3
- "version": "1.4.1",
3
+ "version": "1.4.2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Durable workflows in Convex: one workflow primitive with a task schema, queues on every line, workflow budgets, named end states, events and sub-workflows; worker processes run the steps.",
package/worker/index.ts CHANGED
@@ -7,6 +7,7 @@ export {
7
7
  type ReportedOtherWrite,
8
8
  type TakenStep,
9
9
  type WorkerFunctions,
10
+ type WorkflowBudgets,
10
11
  WorkflowPlatformClient,
11
12
  } from "./platform-client"
12
13
  export { type ServicesOfWorkflows, WorkerLacksService, type WorkerOptions, type WorkerServices, type WorkResult, workForever, workOnce, workUntilIdle } from "./worker"
@@ -1,6 +1,6 @@
1
1
  import type { ConvexHttpClient } from "convex/browser"
2
2
  import type { FunctionReference } from "convex/server"
3
- import { Context, Data, Effect, Schema } from "effect"
3
+ import { Context, Data, Effect, Option, Schema } from "effect"
4
4
  import type { FoundTask, TasksAt } from "../src/definition/tasks"
5
5
  import type { StepMeasurements, TaskFile } from "../src/graph"
6
6
 
@@ -65,8 +65,23 @@ export interface CompleteInput {
65
65
  readonly others?: ReadonlyArray<ReportedOtherWrite>
66
66
  }
67
67
 
68
+ const WorkflowBudgets = Schema.Array(
69
+ Schema.Struct({ workflow: Schema.String, budgets: Schema.NullOr(Schema.Struct({ agents: Schema.Number, cpu: Schema.Number })) }),
70
+ )
71
+ /** Each workflow's budget limits as registered, or null for one not registered. */
72
+ export type WorkflowBudgets = typeof WorkflowBudgets.Type
73
+ const decodeBudgets = Schema.decodeUnknownEffect(WorkflowBudgets)
74
+
68
75
  /** What a worker asks of the workflow platform in Convex: take a task, report on it, and read other tasks for its run. */
69
76
  export interface IWorkflowPlatformClient {
77
+ /**
78
+ * Each workflow's budget limits, so a worker asks `take` only for steps a budget can admit. Every component call in
79
+ * `take` costs tens of milliseconds, and `take` makes one per workflow it is given, so asking for all 30 of a
80
+ * workforce's workflows held each take near a second while nothing could run (2026-11-29). The workforce's `budgets`
81
+ * query reads only the workflow rows, which change only when a workflow registers or its budgets are set, so Convex
82
+ * answers it from its cache. None when the workforce has no `budgets` function: the worker then asks for every step.
83
+ */
84
+ budgets(): Effect.fn.Return<Option.Option<WorkflowBudgets>, PlatformCallFailed>
70
85
  take(input: { readonly worker: string; readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }>; readonly leaseMs: number }): Effect.fn.Return<TakenStep | null, PlatformCallFailed>
71
86
  complete(input: CompleteInput): Effect.fn.Return<void, PlatformCallFailed>
72
87
  fail(input: { readonly workflow: string; readonly run: string; readonly error: string; readonly measurements: StepMeasurements }): Effect.fn.Return<void, PlatformCallFailed>
@@ -91,6 +106,8 @@ export interface WorkerFunctions {
91
106
  readonly fail: FunctionReference<"mutation">
92
107
  readonly heartbeat: FunctionReference<"mutation">
93
108
  readonly findTasks: FunctionReference<"query">
109
+ /** Each workflow's budget limits (`IWorkflowPlatformClient.budgets`); a workforce without it is asked for every step. */
110
+ readonly budgets?: FunctionReference<"query">
94
111
  }
95
112
 
96
113
  export class ConvexWorkflowPlatformClient implements IWorkflowPlatformClient {
@@ -99,13 +116,23 @@ export class ConvexWorkflowPlatformClient implements IWorkflowPlatformClient {
99
116
  private readonly functions: WorkerFunctions,
100
117
  ) {}
101
118
 
102
- private call(name: Exclude<keyof WorkerFunctions, "findTasks">, args: Record<string, unknown>) {
119
+ private call(name: Exclude<keyof WorkerFunctions, "findTasks" | "budgets">, args: Record<string, unknown>) {
103
120
  return Effect.tryPromise({
104
121
  try: (): Promise<unknown> => this.client.mutation(this.functions[name], args),
105
122
  catch: (cause) => new PlatformCallFailed({ call: name, cause }),
106
123
  })
107
124
  }
108
125
 
126
+ *budgets() {
127
+ const maybeBudgets = Option.fromUndefinedOr(this.functions.budgets)
128
+ if (Option.isNone(maybeBudgets)) return Option.none<WorkflowBudgets>()
129
+ const read = yield* Effect.tryPromise({
130
+ try: (): Promise<unknown> => this.client.query(maybeBudgets.value, {}),
131
+ catch: (cause) => new PlatformCallFailed({ call: "budgets", cause }),
132
+ })
133
+ return Option.some(yield* Effect.mapError(decodeBudgets(read), (cause) => new PlatformCallFailed({ call: "budgets", cause })))
134
+ }
135
+
109
136
  *take(input: { readonly worker: string; readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }>; readonly leaseMs: number }) {
110
137
  const taken = yield* this.call("take", { ...input, steps: [...input.steps] })
111
138
  return yield* Effect.mapError(decodeTaken(taken), (cause) => new PlatformCallFailed({ call: "take", cause }))
@@ -1,12 +1,12 @@
1
1
  import { describe, expect, test } from "bun:test"
2
- import { Effect, pipe, Schema } from "effect"
2
+ import { Effect, Option, pipe, Schema } from "effect"
3
3
  import { AgentRunFailed, AgentRunner } from "../src/definition/agent-runner"
4
4
  import { FileStore, FileStoreError } from "../src/definition/file-store"
5
5
  import * as TaskSchema from "../src/definition/task-schema"
6
6
  import * as Workflow from "../src/definition/workflow"
7
7
  import { problemsOf, type StepMeasurements, type TaskFile } from "../src/graph"
8
- import { type IWorkflowPlatformClient, PlatformCallFailed, type TakenStep, WorkflowPlatformClient } from "./platform-client"
9
- import { workOnce } from "./worker"
8
+ import { type IWorkflowPlatformClient, PlatformCallFailed, type TakenStep, type WorkflowBudgets, WorkflowPlatformClient } from "./platform-client"
9
+ import { admittedSteps, workOnce } from "./worker"
10
10
 
11
11
  const counted = Workflow.make({
12
12
  name: "counted",
@@ -36,8 +36,17 @@ const timedOut = (call: string) => new PlatformCallFailed({ call, cause: "Functi
36
36
  class FakePlatform implements IWorkflowPlatformClient {
37
37
  readonly calls: Array<string> = []
38
38
  readonly failures: Array<string> = []
39
- constructor(private readonly answers: { readonly complete: boolean; readonly fail: boolean }) {}
40
- *take() {
39
+ readonly takes: Array<ReadonlyArray<{ readonly workflow: string; readonly step: string }>> = []
40
+ constructor(
41
+ private readonly answers: { readonly complete: boolean; readonly fail: boolean },
42
+ private readonly budgetsRead: Option.Option<WorkflowBudgets> | "fails" = Option.none(),
43
+ ) {}
44
+ *budgets() {
45
+ if (this.budgetsRead === "fails") return yield* Effect.fail(timedOut("budgets"))
46
+ return this.budgetsRead
47
+ }
48
+ *take(input: { readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }> }) {
49
+ this.takes.push(input.steps)
41
50
  return taken
42
51
  }
43
52
  *complete() {
@@ -90,6 +99,35 @@ describe("a worker reporting to a platform that times out", () => {
90
99
  })
91
100
  })
92
101
 
102
+ describe("asking take only where a budget can admit", () => {
103
+ const budgetsOf = (cpu: number) => Option.some([{ workflow: "counted", budgets: { agents: 0, cpu } }])
104
+
105
+ test("a workflow held at 0 is not asked about: the worker is idle without a take", async () => {
106
+ const platform = new FakePlatform({ complete: true, fail: true }, budgetsOf(0))
107
+ expect(await workWith(platform)).toEqual({ _tag: "Idle" })
108
+ expect(platform.takes).toEqual([])
109
+ })
110
+
111
+ test("a workflow whose budget admits its step is asked about", async () => {
112
+ const platform = new FakePlatform({ complete: true, fail: true }, budgetsOf(1))
113
+ expect((await workWith(platform))._tag).toBe("Ran")
114
+ expect(platform.takes).toEqual([[{ workflow: "counted", step: "count" }]])
115
+ })
116
+
117
+ test("with no budgets function, or a failed read, every step is asked about", async () => {
118
+ for (const read of [Option.none<WorkflowBudgets>(), "fails" as const]) {
119
+ const platform = new FakePlatform({ complete: true, fail: true }, read)
120
+ expect((await workWith(platform))._tag).toBe("Ran")
121
+ expect(platform.takes).toEqual([[{ workflow: "counted", step: "count" }]])
122
+ }
123
+ })
124
+
125
+ test("an agent step is kept by the agents' budget, and an unregistered workflow keeps its steps", () => {
126
+ const steps = [{ workflow: "counted", step: "count" }, { workflow: "other", step: "think" }]
127
+ expect(admittedSteps({ steps, workflows: [counted], budgets: Option.some([{ workflow: "counted", budgets: { agents: 1, cpu: 0 } }, { workflow: "other", budgets: null }]) })).toEqual([{ workflow: "other", step: "think" }])
128
+ })
129
+ })
130
+
93
131
  describe("what a step may use", () => {
94
132
  /** A step that asks for the agent runner; whether it declared it decides whether it compiles and whether it gets it. */
95
133
  const asksForAgents = function* () {
package/worker/worker.ts CHANGED
@@ -4,8 +4,8 @@ import { FileStore } from "../src/definition/file-store"
4
4
  import { ProgramBuild } from "../src/definition/program-build"
5
5
  import { Tasks } from "../src/definition/tasks"
6
6
  import type { WorkflowDefinition } from "../src/definition/workflow"
7
- import { nothingUsed, noSpend, type StepMeasurements, type TaskFile } from "../src/graph"
8
- import { type PlatformCallFailed, type ReportedOtherWrite, type TakenStep, WorkflowPlatformClient } from "./platform-client"
7
+ import { budgetOfStepKind, nothingUsed, noSpend, type StepMeasurements, type TaskFile } from "../src/graph"
8
+ import { type PlatformCallFailed, type ReportedOtherWrite, type TakenStep, type WorkflowBudgets, WorkflowPlatformClient } from "./platform-client"
9
9
  import { StepMeter } from "./step-meter"
10
10
  import { RunTasks } from "./worker-tasks"
11
11
 
@@ -51,6 +51,27 @@ const checkServices = function* (input: { readonly workflows: ReadonlyArray<Work
51
51
  }
52
52
  }
53
53
 
54
+ /**
55
+ * Of `steps`, those whose workflow's budget for the step's kind is above 0, so `take` is asked only where it can give
56
+ * a task: each workflow it is asked about costs it a component call. A workflow with no budgets on record (not
57
+ * registered) keeps its steps, so `take` says why; with no budgets read at all, every step is kept. Pure.
58
+ */
59
+ export const admittedSteps = (input: {
60
+ readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }>
61
+ readonly workflows: ReadonlyArray<WorkflowDefinition<any, any, any>>
62
+ readonly budgets: Option.Option<WorkflowBudgets>
63
+ }): ReadonlyArray<{ readonly workflow: string; readonly step: string }> => {
64
+ if (Option.isNone(input.budgets)) return input.steps
65
+ const limits = new Map(input.budgets.value.map((row) => [row.workflow, row.budgets]))
66
+ return input.steps.filter(({ workflow, step }) => {
67
+ const budgets = limits.get(workflow)
68
+ if (budgets === undefined || budgets === null) return true
69
+ const kind = input.workflows.find((w) => w.name === workflow)?.graph.steps.find((s) => s.id === step)?.kind
70
+ const budget = kind === undefined ? "none" : budgetOfStepKind(kind)
71
+ return budget !== "none" && budgets[budget] > 0
72
+ })
73
+ }
74
+
54
75
  /**
55
76
  * Takes one task from Convex, runs its step with only the services the step declares, and reports the end state with
56
77
  * the task's changed fields and files and the step's writes to other tasks. A step that fails or dies is reported as
@@ -70,7 +91,12 @@ const runOnce = function* <Services>(input: {
70
91
  }): Effect.fn.Return<WorkResult, unknown, WorkerServices<Services>> {
71
92
  const options = input.options
72
93
  const client = yield* WorkflowPlatformClient
73
- const steps = options.workflows.flatMap((workflow) => Object.keys(workflow.runnableSteps).map((step) => ({ workflow: workflow.name, step })))
94
+ const all = options.workflows.flatMap((workflow) => Object.keys(workflow.runnableSteps).map((step) => ({ workflow: workflow.name, step })))
95
+ // A budgets read that fails costs only the saving: every step is asked for, as before it existed.
96
+ const read = yield* Effect.result(Effect.gen(() => client.budgets()))
97
+ if (Result.isFailure(read)) yield* Effect.logWarning(`worker ${options.worker} could not read the budgets, so it asks for every step: ${read.failure.message}`)
98
+ const steps = admittedSteps({ steps: all, workflows: options.workflows, budgets: Result.isSuccess(read) ? read.success : Option.none() })
99
+ if (steps.length === 0) return { _tag: "Idle" }
74
100
  // Workers racing for one queue head can exhaust Convex's own retries; the loser asks again after a jittered wait,
75
101
  // for about 5 seconds in all, since a loaded machine can take a second over each take.
76
102
  const taken = yield* pipe(