@jive-sh/workflow-platform 0.6.3 → 1.0.0
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/README.md +66 -295
- package/component/_generated/api.ts +72 -0
- package/component/_generated/component.ts +621 -0
- package/component/_generated/dataModel.ts +60 -0
- package/component/_generated/server.ts +169 -0
- package/component/convex.config.ts +3 -0
- package/component/engine.ts +755 -0
- package/component/errors.ts +66 -0
- package/component/events.ts +17 -0
- package/component/notes.ts +13 -0
- package/component/places.ts +136 -0
- package/component/retention.ts +205 -0
- package/component/runEngine.ts +25 -0
- package/component/schema.ts +132 -0
- package/component/steps.ts +188 -0
- package/component/store.ts +512 -0
- package/component/tasks.ts +289 -0
- package/component/worker.ts +109 -0
- package/component/workflows.ts +83 -0
- package/dist/definition/agent-runner.js +9 -0
- package/dist/definition/agent-runner.js.map +1 -0
- package/dist/definition/file-store.js +9 -0
- package/dist/definition/file-store.js.map +1 -0
- package/dist/definition/program-build.js +10 -0
- package/dist/definition/program-build.js.map +1 -0
- package/dist/definition/step.js +1 -0
- package/dist/definition/step.js.map +1 -0
- package/dist/definition/task-schema.js +5 -0
- package/dist/definition/task-schema.js.map +1 -0
- package/dist/definition/tasks.js +9 -0
- package/dist/definition/tasks.js.map +1 -0
- package/dist/definition/workflow.js +111 -0
- package/dist/definition/workflow.js.map +1 -0
- package/dist/graph.js +301 -9
- package/dist/graph.js.map +1 -1
- package/dist/index.js +7 -133
- package/dist/index.js.map +1 -1
- package/package.json +9 -4
- package/src/definition/agent-runner.ts +59 -0
- package/src/definition/file-store.ts +20 -0
- package/src/definition/program-build.ts +30 -0
- package/src/definition/step.ts +106 -0
- package/src/definition/task-schema.ts +15 -0
- package/src/definition/tasks.ts +43 -0
- package/src/definition/workflow.ts +255 -0
- package/src/graph.ts +341 -19
- package/src/index.ts +8 -168
- package/worker/directory-file-store.ts +42 -0
- package/worker/index.ts +12 -0
- package/worker/platform-client.ts +138 -0
- package/worker/step-meter.ts +80 -0
- package/worker/worker-tasks.ts +27 -0
- package/worker/worker.test.ts +200 -0
- package/worker/worker.ts +240 -0
- package/dist/budget-states.js +0 -30
- package/dist/budget-states.js.map +0 -1
- package/dist/cpu-limit/limiter.js +0 -839
- package/dist/cpu-limit/limiter.js.map +0 -1
- package/dist/cpu-limit/use.js +0 -139
- package/dist/cpu-limit/use.js.map +0 -1
- package/dist/dashboard/agent-usage.js +0 -25
- package/dist/dashboard/agent-usage.js.map +0 -1
- package/dist/dashboard/dashboard.css +0 -134
- package/dist/dashboard/drilldown.js +0 -16
- package/dist/dashboard/drilldown.js.map +0 -1
- package/dist/dashboard/queue-lines.js +0 -44
- package/dist/dashboard/queue-lines.js.map +0 -1
- package/dist/dashboard/queue-table.js +0 -16
- package/dist/dashboard/queue-table.js.map +0 -1
- package/dist/dashboard/spending-words.js +0 -32
- package/dist/dashboard/spending-words.js.map +0 -1
- package/dist/failure.js +0 -35
- package/dist/failure.js.map +0 -1
- package/dist/keep-running.js +0 -77
- package/dist/keep-running.js.map +0 -1
- package/dist/outside-failure.js +0 -31
- package/dist/outside-failure.js.map +0 -1
- package/dist/pick-wakes.js +0 -125
- package/dist/pick-wakes.js.map +0 -1
- package/dist/project.js +0 -1
- package/dist/project.js.map +0 -1
- package/dist/queue-counts.js +0 -51
- package/dist/queue-counts.js.map +0 -1
- package/dist/reasons.js +0 -33
- package/dist/reasons.js.map +0 -1
- package/dist/spending-limit.js +0 -88
- package/dist/spending-limit.js.map +0 -1
- package/dist/step-files.js +0 -200
- package/dist/step-files.js.map +0 -1
- package/dist/step-meter.js +0 -97
- package/dist/step-meter.js.map +0 -1
- package/dist/step-usage.js +0 -19
- package/dist/step-usage.js.map +0 -1
- package/dist/steps.js +0 -920
- package/dist/steps.js.map +0 -1
- package/dist/storage/budgets.js +0 -85
- package/dist/storage/budgets.js.map +0 -1
- package/dist/storage/engine-records.js +0 -75
- package/dist/storage/engine-records.js.map +0 -1
- package/dist/storage/engine-storage.js +0 -67
- package/dist/storage/engine-storage.js.map +0 -1
- package/dist/storage/input-records.js +0 -12
- package/dist/storage/input-records.js.map +0 -1
- package/dist/storage/move-store.js +0 -251
- package/dist/storage/move-store.js.map +0 -1
- package/dist/storage/sqlite-store.js +0 -723
- package/dist/storage/sqlite-store.js.map +0 -1
- package/dist/storage/step-records.js +0 -11
- package/dist/storage/step-records.js.map +0 -1
- package/dist/storage/storage-error.js +0 -19
- package/dist/storage/storage-error.js.map +0 -1
- package/dist/storage/task-store.js +0 -24
- package/dist/storage/task-store.js.map +0 -1
- package/dist/tasks.js +0 -475
- package/dist/tasks.js.map +0 -1
- package/dist/views/format.js +0 -37
- package/dist/views/format.js.map +0 -1
- package/dist/views/runs-now.js +0 -75
- package/dist/views/runs-now.js.map +0 -1
- package/dist/views/step-funnel.js +0 -98
- package/dist/views/step-funnel.js.map +0 -1
- package/dist/views/step-graph.js +0 -34
- package/dist/views/step-graph.js.map +0 -1
- package/dist/views/workflow-flows.js +0 -53
- package/dist/views/workflow-flows.js.map +0 -1
- package/dist/views/workflows-view.js +0 -230
- package/dist/views/workflows-view.js.map +0 -1
- package/src/budget-states.ts +0 -55
- package/src/cpu-limit/limiter.ts +0 -935
- package/src/cpu-limit/use.ts +0 -166
- package/src/dashboard/agent-usage-line.tsx +0 -28
- package/src/dashboard/agent-usage.ts +0 -48
- package/src/dashboard/dashboard.css +0 -134
- package/src/dashboard/drilldown.ts +0 -43
- package/src/dashboard/index.tsx +0 -4
- package/src/dashboard/machine-controls.tsx +0 -53
- package/src/dashboard/queue-bar.tsx +0 -43
- package/src/dashboard/queue-chart.tsx +0 -150
- package/src/dashboard/queue-lines.ts +0 -87
- package/src/dashboard/queue-table.ts +0 -37
- package/src/dashboard/spending-limit-control.tsx +0 -50
- package/src/dashboard/spending-words.ts +0 -50
- package/src/dashboard/step-graph.tsx +0 -106
- package/src/dashboard/workflow-dag.tsx +0 -204
- package/src/dashboard/workflow-drilldown.tsx +0 -89
- package/src/dashboard/workflows-dashboard.tsx +0 -414
- package/src/failure.ts +0 -36
- package/src/keep-running.ts +0 -83
- package/src/outside-failure.ts +0 -39
- package/src/pick-wakes.ts +0 -182
- package/src/project.ts +0 -115
- package/src/queue-counts.ts +0 -64
- package/src/reasons.ts +0 -30
- package/src/spending-limit.ts +0 -156
- package/src/step-files.ts +0 -208
- package/src/step-meter.ts +0 -120
- package/src/step-usage.ts +0 -23
- package/src/steps.ts +0 -1239
- package/src/storage/budgets.ts +0 -113
- package/src/storage/engine-records.ts +0 -102
- package/src/storage/engine-storage.ts +0 -82
- package/src/storage/input-records.ts +0 -43
- package/src/storage/move-store.ts +0 -265
- package/src/storage/sqlite-store.ts +0 -829
- package/src/storage/step-records.ts +0 -306
- package/src/storage/storage-error.ts +0 -35
- package/src/storage/task-store.ts +0 -235
- package/src/tasks.ts +0 -561
- package/src/views/format.ts +0 -40
- package/src/views/runs-now.ts +0 -120
- package/src/views/step-funnel.ts +0 -163
- package/src/views/step-graph.ts +0 -68
- package/src/views/workflow-flows.ts +0 -97
- package/src/views/workflows-view.ts +0 -443
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { Data } from "effect"
|
|
2
|
+
|
|
3
|
+
export class WorkflowNotRegistered extends Data.TaggedError("WorkflowNotRegistered")<{ readonly workflow: string }> {
|
|
4
|
+
override get message() {
|
|
5
|
+
return `workflow ${this.workflow} is not registered`
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class InvalidGraph extends Data.TaggedError("InvalidGraph")<{ readonly workflow: string; readonly problems: ReadonlyArray<string> }> {
|
|
10
|
+
override get message() {
|
|
11
|
+
return `workflow ${this.workflow} is invalid: ${this.problems.join("; ")}`
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class StepNotFound extends Data.TaggedError("StepNotFound")<{ readonly workflow: string; readonly step: string }> {
|
|
16
|
+
override get message() {
|
|
17
|
+
return `workflow ${this.workflow} has no step ${this.step}`
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export class UnknownEndState extends Data.TaggedError("UnknownEndState")<{ readonly workflow: string; readonly step: string; readonly endState: string }> {
|
|
22
|
+
override get message() {
|
|
23
|
+
return `step ${this.step} of workflow ${this.workflow} has no end state ${this.endState}`
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class UnknownEvent extends Data.TaggedError("UnknownEvent")<{ readonly workflow: string; readonly event: string }> {
|
|
28
|
+
override get message() {
|
|
29
|
+
return `workflow ${this.workflow} has no event ${this.event} that creates tasks`
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class TaskNotFound extends Data.TaggedError("TaskNotFound")<{ readonly task: string }> {
|
|
34
|
+
override get message() {
|
|
35
|
+
return `task ${this.task} does not exist`
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class InvalidTaskFields extends Data.TaggedError("InvalidTaskFields")<{ readonly task: string; readonly problem: string }> {
|
|
40
|
+
override get message() {
|
|
41
|
+
return `task ${this.task} has invalid fields: ${this.problem}`
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class StepRunNotRunning extends Data.TaggedError("StepRunNotRunning")<{ readonly run: string; readonly status: string }> {
|
|
46
|
+
override get message() {
|
|
47
|
+
return `step run ${this.run} is ${this.status}, not running`
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export class TaskInProgress extends Data.TaggedError("TaskInProgress")<{ readonly task: string; readonly step: string }> {
|
|
52
|
+
override get message() {
|
|
53
|
+
return `task ${this.task} is in step ${this.step} now, so it cannot be sent back until that step ends`
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type EngineError =
|
|
58
|
+
| WorkflowNotRegistered
|
|
59
|
+
| InvalidGraph
|
|
60
|
+
| StepNotFound
|
|
61
|
+
| UnknownEndState
|
|
62
|
+
| UnknownEvent
|
|
63
|
+
| TaskNotFound
|
|
64
|
+
| InvalidTaskFields
|
|
65
|
+
| StepRunNotRunning
|
|
66
|
+
| TaskInProgress
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { v } from "convex/values"
|
|
2
|
+
import { internalMutation } from "./_generated/server"
|
|
3
|
+
import * as Engine from "./engine"
|
|
4
|
+
import { runEngine } from "./runEngine"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A timer event fired: it brings a new task with the event's fields into its workflow, and schedules its next firing. A
|
|
8
|
+
* tick of a registration since replaced or removed (another `generation`, or none) stops.
|
|
9
|
+
*/
|
|
10
|
+
export const timerTick = internalMutation({
|
|
11
|
+
args: { workflow: v.string(), event: v.string(), generation: v.optional(v.number()) },
|
|
12
|
+
returns: v.null(),
|
|
13
|
+
handler: async (ctx, args) => {
|
|
14
|
+
await runEngine(ctx, Engine.timerFired(args))
|
|
15
|
+
return null
|
|
16
|
+
},
|
|
17
|
+
})
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { TaskNote } from "../src/graph"
|
|
2
|
+
import type { Doc } from "./_generated/dataModel"
|
|
3
|
+
|
|
4
|
+
/** Everything said about a task, oldest first: its step runs' notes, at when the run ended, and the notes calls left. */
|
|
5
|
+
export const notesOf = (input: {
|
|
6
|
+
readonly task: Doc<"tasks">
|
|
7
|
+
readonly runs: ReadonlyArray<Doc<"stepRuns">>
|
|
8
|
+
readonly left: ReadonlyArray<Doc<"taskNotes">>
|
|
9
|
+
}): Array<TaskNote> =>
|
|
10
|
+
[
|
|
11
|
+
...input.runs.flatMap((run) => (run.note === undefined ? [] : [{ workflow: input.task.workflow, step: run.step, note: run.note, at: run.endedAt ?? run.startedAt }])),
|
|
12
|
+
...input.left.map((row) => ({ workflow: input.task.workflow, ...(row.step !== undefined ? { step: row.step } : {}), note: row.note, at: row.at })),
|
|
13
|
+
].sort((a, b) => a.at - b.at)
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { paginationOptsValidator } from "convex/server"
|
|
2
|
+
import { v } from "convex/values"
|
|
3
|
+
import { inputPlacesOf, placeAtStartOf, placeRefValidator } from "../src/graph"
|
|
4
|
+
import type { Doc } from "./_generated/dataModel"
|
|
5
|
+
import { type QueryCtx, query } from "./_generated/server"
|
|
6
|
+
import { notesOf } from "./notes"
|
|
7
|
+
|
|
8
|
+
/** The latest thing said about a task, by a step or by a call that sent it back, or undefined when nothing has been. */
|
|
9
|
+
const latestNoteOf = async (ctx: QueryCtx, task: Doc<"tasks">): Promise<string | undefined> => {
|
|
10
|
+
const runs = await ctx.db.query("stepRuns").withIndex("by_task", (q) => q.eq("task", task._id)).collect()
|
|
11
|
+
const left = await ctx.db.query("taskNotes").withIndex("by_task", (q) => q.eq("task", task._id)).collect()
|
|
12
|
+
return notesOf({ task, runs, left }).at(-1)?.note
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Queue order, the order a step takes its tasks in: longest waiting first, the earlier-made flow first on a tie. */
|
|
16
|
+
const inQueueOrder = (a: Doc<"flows">, b: Doc<"flows">) => a.enteredAt - b.enteredAt || a._creationTime - b._creationTime
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* One page of every task waiting in front of a step, across all the lines into it, in the order the step takes them.
|
|
20
|
+
* The cursor is the queue position (`enteredAt` and creation time) of the last task of the page before.
|
|
21
|
+
*/
|
|
22
|
+
const pageInFrontOf = async (
|
|
23
|
+
ctx: QueryCtx,
|
|
24
|
+
input: { readonly workflow: Doc<"workflows">; readonly step: string; readonly numItems: number; readonly cursor: string | null },
|
|
25
|
+
) => {
|
|
26
|
+
if (!input.workflow.graph.steps.some((step) => step.id === input.step)) throw new Error(`workflow ${input.workflow.name} has no step ${input.step}`)
|
|
27
|
+
const parts = input.cursor === null || input.cursor === "" ? null : input.cursor.split(":").map(Number)
|
|
28
|
+
if (parts !== null && (parts.length !== 2 || parts.some((part) => !Number.isFinite(part)))) throw new Error(`invalid cursor ${input.cursor}`)
|
|
29
|
+
const after = parts === null ? null : { enteredAt: parts[0]!, creationTime: parts[1]! }
|
|
30
|
+
const wanted = input.numItems + 1
|
|
31
|
+
const flows: Array<Doc<"flows">> = []
|
|
32
|
+
for (const place of inputPlacesOf(input.workflow.graph, input.step)) {
|
|
33
|
+
if (after === null) {
|
|
34
|
+
flows.push(...(await ctx.db.query("flows").withIndex("by_workflow_place_entered", (q) => q.eq("workflow", input.workflow.name).eq("place", place)).take(wanted)))
|
|
35
|
+
continue
|
|
36
|
+
}
|
|
37
|
+
const { enteredAt, creationTime } = after
|
|
38
|
+
flows.push(
|
|
39
|
+
...(await ctx.db
|
|
40
|
+
.query("flows")
|
|
41
|
+
.withIndex("by_workflow_place_entered", (q) =>
|
|
42
|
+
q.eq("workflow", input.workflow.name).eq("place", place).eq("enteredAt", enteredAt).gt("_creationTime", creationTime),
|
|
43
|
+
)
|
|
44
|
+
.take(wanted)),
|
|
45
|
+
...(await ctx.db
|
|
46
|
+
.query("flows")
|
|
47
|
+
.withIndex("by_workflow_place_entered", (q) => q.eq("workflow", input.workflow.name).eq("place", place).gt("enteredAt", enteredAt))
|
|
48
|
+
.take(wanted)),
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
const sorted = flows.sort(inQueueOrder)
|
|
52
|
+
const page = sorted.slice(0, input.numItems)
|
|
53
|
+
const last = page.at(-1)
|
|
54
|
+
return {
|
|
55
|
+
page,
|
|
56
|
+
isDone: sorted.length <= input.numItems,
|
|
57
|
+
continueCursor: last === undefined ? (input.cursor ?? "") : `${last.enteredAt}:${last._creationTime}`,
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The tasks at one place of a workflow, oldest first, a page at a time: waiting on a line (a line out of an end state
|
|
63
|
+
* lists the tasks waiting at that end state, since they are its queue), waiting in front of a step on any line into it
|
|
64
|
+
* (in the order the step takes them), in a step, or at an end state. A task in a step comes with the run that holds
|
|
65
|
+
* it, and every task with the latest note a step left on it.
|
|
66
|
+
*/
|
|
67
|
+
export const tasksAt = query({
|
|
68
|
+
args: { workflow: v.string(), place: placeRefValidator, paginationOpts: paginationOptsValidator },
|
|
69
|
+
returns: v.object({
|
|
70
|
+
page: v.array(
|
|
71
|
+
v.object({
|
|
72
|
+
task: v.id("tasks"),
|
|
73
|
+
fields: v.any(),
|
|
74
|
+
startedBy: v.string(),
|
|
75
|
+
enteredAt: v.number(),
|
|
76
|
+
note: v.optional(v.string()),
|
|
77
|
+
run: v.optional(
|
|
78
|
+
v.object({ worker: v.optional(v.string()), startedAt: v.number(), call: v.number(), heartbeatAt: v.optional(v.number()) }),
|
|
79
|
+
),
|
|
80
|
+
}),
|
|
81
|
+
),
|
|
82
|
+
isDone: v.boolean(),
|
|
83
|
+
continueCursor: v.string(),
|
|
84
|
+
}),
|
|
85
|
+
handler: async (ctx, args) => {
|
|
86
|
+
const workflow = await ctx.db.query("workflows").withIndex("by_name", (q) => q.eq("name", args.workflow)).unique()
|
|
87
|
+
if (workflow === null) throw new Error(`workflow ${args.workflow} is not registered`)
|
|
88
|
+
const asked = args.place
|
|
89
|
+
let place = ""
|
|
90
|
+
if ("line" in asked) {
|
|
91
|
+
const line = workflow.graph.lines.find((candidate) => candidate.id === asked.line)
|
|
92
|
+
if (line === undefined) throw new Error(`workflow ${args.workflow} has no line ${asked.line}`)
|
|
93
|
+
place = placeAtStartOf(line)
|
|
94
|
+
} else if ("step" in asked) {
|
|
95
|
+
place = `step:${asked.step}`
|
|
96
|
+
} else if ("end" in asked) {
|
|
97
|
+
place = `end:${asked.end}`
|
|
98
|
+
}
|
|
99
|
+
const result =
|
|
100
|
+
"inFrontOf" in asked
|
|
101
|
+
? await pageInFrontOf(ctx, { workflow, step: asked.inFrontOf, numItems: args.paginationOpts.numItems, cursor: args.paginationOpts.cursor })
|
|
102
|
+
: await ctx.db
|
|
103
|
+
.query("flows")
|
|
104
|
+
.withIndex("by_workflow_place_entered", (q) => q.eq("workflow", args.workflow).eq("place", place))
|
|
105
|
+
.order("asc")
|
|
106
|
+
.paginate(args.paginationOpts)
|
|
107
|
+
const page = []
|
|
108
|
+
for (const flow of result.page) {
|
|
109
|
+
const task = await ctx.db.get(flow.task)
|
|
110
|
+
if (task === null) continue
|
|
111
|
+
const run = flow.place.startsWith("step:")
|
|
112
|
+
? await ctx.db.query("stepRuns").withIndex("by_flow_status", (q) => q.eq("flow", flow._id).eq("status", "running")).unique()
|
|
113
|
+
: null
|
|
114
|
+
const lease = run === null ? null : await ctx.db.query("leases").withIndex("by_run", (q) => q.eq("run", run._id)).unique()
|
|
115
|
+
const note = await latestNoteOf(ctx, task)
|
|
116
|
+
page.push({
|
|
117
|
+
task: task._id,
|
|
118
|
+
fields: task.fields,
|
|
119
|
+
startedBy: flow.startedBy,
|
|
120
|
+
enteredAt: flow.enteredAt,
|
|
121
|
+
...(note !== undefined ? { note } : {}),
|
|
122
|
+
...(run !== null
|
|
123
|
+
? {
|
|
124
|
+
run: {
|
|
125
|
+
startedAt: run.startedAt,
|
|
126
|
+
call: run.call,
|
|
127
|
+
...(run.worker !== undefined ? { worker: run.worker } : {}),
|
|
128
|
+
...(lease !== null ? { heartbeatAt: lease.heartbeatAt } : {}),
|
|
129
|
+
},
|
|
130
|
+
}
|
|
131
|
+
: {}),
|
|
132
|
+
})
|
|
133
|
+
}
|
|
134
|
+
return { page, isDone: result.isDone, continueCursor: result.continueCursor }
|
|
135
|
+
},
|
|
136
|
+
})
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { paginationOptsValidator } from "convex/server"
|
|
2
|
+
import { v } from "convex/values"
|
|
3
|
+
import { retentionOf } from "../src/graph"
|
|
4
|
+
import { internal } from "./_generated/api"
|
|
5
|
+
import type { Id } from "./_generated/dataModel"
|
|
6
|
+
import { action, type ActionCtx, internalAction, internalMutation, internalQuery, type MutationCtx } from "./_generated/server"
|
|
7
|
+
import { PRUNE_EVERY_MS } from "./store"
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* RETENTION: once a day each workflow deletes the records it no longer keeps (`retentionOf` in `graph.ts`, where what
|
|
11
|
+
* it keeps is written down). A pass pages through the records in transactions of its own, so keeping a step's newest
|
|
12
|
+
* 10,000 runs never reads them in one, and deletes in batches.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const PAGE = 500
|
|
16
|
+
const passValidator = v.object({ runs: v.number(), turnTasks: v.number() })
|
|
17
|
+
|
|
18
|
+
/** One page of a step's runs, newest first: what a pass needs to judge each. */
|
|
19
|
+
export const runsPage = internalQuery({
|
|
20
|
+
args: { workflow: v.string(), step: v.string(), paginationOpts: paginationOptsValidator },
|
|
21
|
+
handler: async (ctx, args) => {
|
|
22
|
+
const page = await ctx.db
|
|
23
|
+
.query("stepRuns")
|
|
24
|
+
.withIndex("by_workflow_step_started", (q) => q.eq("workflow", args.workflow).eq("step", args.step))
|
|
25
|
+
.order("desc")
|
|
26
|
+
.paginate(args.paginationOpts)
|
|
27
|
+
return { ...page, page: page.page.map((run) => ({ run: run._id, status: run.status, endedAt: run.endedAt ?? null })) }
|
|
28
|
+
},
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
/** One page of the flows waiting at a place, newest first, with the event that started each. */
|
|
32
|
+
export const flowsPage = internalQuery({
|
|
33
|
+
args: { workflow: v.string(), place: v.string(), paginationOpts: paginationOptsValidator },
|
|
34
|
+
handler: async (ctx, args) => {
|
|
35
|
+
const page = await ctx.db
|
|
36
|
+
.query("flows")
|
|
37
|
+
.withIndex("by_workflow_place_entered", (q) => q.eq("workflow", args.workflow).eq("place", args.place))
|
|
38
|
+
.order("desc")
|
|
39
|
+
.paginate(args.paginationOpts)
|
|
40
|
+
return { ...page, page: page.page.map((flow) => ({ task: flow.task, startedBy: flow.startedBy, enteredAt: flow.enteredAt })) }
|
|
41
|
+
},
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
/** The graph a pass judges by, or null for a workflow not registered. */
|
|
45
|
+
export const graphOf = internalQuery({
|
|
46
|
+
args: { workflow: v.string() },
|
|
47
|
+
handler: async (ctx, args) => (await ctx.db.query("workflows").withIndex("by_name", (q) => q.eq("name", args.workflow)).unique())?.graph ?? null,
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
const deleteRunRow = async (ctx: MutationCtx, run: Id<"stepRuns">) => {
|
|
51
|
+
const lease = await ctx.db.query("leases").withIndex("by_run", (q) => q.eq("run", run)).unique()
|
|
52
|
+
if (lease !== null) await ctx.db.delete(lease._id)
|
|
53
|
+
await ctx.db.delete(run)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Deletes these runs where each still qualifies: over, ended before `before`, and of a task that has ended. A run's
|
|
58
|
+
* note stays on its task, as a task note at the time the run ended, so the task's history keeps what it said.
|
|
59
|
+
*/
|
|
60
|
+
export const deleteRuns = internalMutation({
|
|
61
|
+
args: { runs: v.array(v.id("stepRuns")), before: v.number() },
|
|
62
|
+
returns: v.number(),
|
|
63
|
+
handler: async (ctx, args) => {
|
|
64
|
+
let deleted = 0
|
|
65
|
+
for (const id of args.runs) {
|
|
66
|
+
const run = await ctx.db.get(id)
|
|
67
|
+
if (run === null || run.status === "running" || run.endedAt === undefined || run.endedAt >= args.before) continue
|
|
68
|
+
const task = await ctx.db.get(run.task)
|
|
69
|
+
if (task !== null && task.endedAs === undefined) continue
|
|
70
|
+
if (task !== null && run.note !== undefined) await ctx.db.insert("taskNotes", { task: task._id, note: run.note, at: run.endedAt, step: run.step })
|
|
71
|
+
await deleteRunRow(ctx, id)
|
|
72
|
+
deleted += 1
|
|
73
|
+
}
|
|
74
|
+
return deleted
|
|
75
|
+
},
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
/** Deletes these turn tasks where each still qualifies (ended, a timer made it), with their flows, runs and notes. */
|
|
79
|
+
export const deleteTurnTasks = internalMutation({
|
|
80
|
+
args: { workflow: v.string(), tasks: v.array(v.id("tasks")) },
|
|
81
|
+
returns: v.object({ tasks: v.number(), runs: v.number() }),
|
|
82
|
+
handler: async (ctx, args) => {
|
|
83
|
+
const workflow = await ctx.db.query("workflows").withIndex("by_name", (q) => q.eq("name", args.workflow)).unique()
|
|
84
|
+
const timers = new Set((workflow?.graph.events ?? []).filter((event) => event.kind === "timer").map((event) => event.id))
|
|
85
|
+
let tasks = 0
|
|
86
|
+
let runs = 0
|
|
87
|
+
for (const id of args.tasks) {
|
|
88
|
+
const task = await ctx.db.get(id)
|
|
89
|
+
if (task === null || task.endedAs === undefined) continue
|
|
90
|
+
const flows = await ctx.db.query("flows").withIndex("by_task_started_by", (q) => q.eq("task", id)).collect()
|
|
91
|
+
if (!flows.some((flow) => timers.has(flow.startedBy))) continue
|
|
92
|
+
for (const flow of flows) {
|
|
93
|
+
for (const row of await ctx.db.query("subWorkflowTasks").withIndex("by_flow_entry", (q) => q.eq("flow", flow._id)).collect()) await ctx.db.delete(row._id)
|
|
94
|
+
await ctx.db.delete(flow._id)
|
|
95
|
+
}
|
|
96
|
+
for (const run of await ctx.db.query("stepRuns").withIndex("by_task", (q) => q.eq("task", id)).collect()) {
|
|
97
|
+
await deleteRunRow(ctx, run._id)
|
|
98
|
+
runs += 1
|
|
99
|
+
}
|
|
100
|
+
for (const note of await ctx.db.query("taskNotes").withIndex("by_task", (q) => q.eq("task", id)).collect()) await ctx.db.delete(note._id)
|
|
101
|
+
await ctx.db.delete(id)
|
|
102
|
+
tasks += 1
|
|
103
|
+
}
|
|
104
|
+
return { tasks, runs }
|
|
105
|
+
},
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
/** Records a pass on its workflow and schedules the next, a day on. */
|
|
109
|
+
export const recordPass = internalMutation({
|
|
110
|
+
args: { workflow: v.string(), at: v.number(), runs: v.number(), turnTasks: v.number(), scheduleNext: v.boolean() },
|
|
111
|
+
returns: v.null(),
|
|
112
|
+
handler: async (ctx, args) => {
|
|
113
|
+
const workflow = await ctx.db.query("workflows").withIndex("by_name", (q) => q.eq("name", args.workflow)).unique()
|
|
114
|
+
if (workflow === null) return null
|
|
115
|
+
const pruning = args.scheduleNext ? { pruning: await ctx.scheduler.runAfter(PRUNE_EVERY_MS, internal.retention.scheduledPass, { workflow: args.workflow }) } : {}
|
|
116
|
+
await ctx.db.patch(workflow._id, { lastPruned: { at: args.at, runs: args.runs, turnTasks: args.turnTasks }, ...pruning })
|
|
117
|
+
return null
|
|
118
|
+
},
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
/** Pages through `page` newest first, passing on every item after the newest `keep` that `qualifies`, in batches. */
|
|
122
|
+
const pastTheNewest = async <Item>(input: {
|
|
123
|
+
readonly page: (cursor: string | null) => Promise<{ readonly page: ReadonlyArray<Item>; readonly isDone: boolean; readonly continueCursor: string }>
|
|
124
|
+
readonly keep: number
|
|
125
|
+
readonly qualifies: (item: Item) => boolean
|
|
126
|
+
readonly remove: (items: ReadonlyArray<Item>) => Promise<void>
|
|
127
|
+
}) => {
|
|
128
|
+
let seen = 0
|
|
129
|
+
let cursor: string | null = null
|
|
130
|
+
while (true) {
|
|
131
|
+
const page = await input.page(cursor)
|
|
132
|
+
const past = page.page.filter((_, index) => seen + index >= input.keep).filter(input.qualifies)
|
|
133
|
+
seen += page.page.length
|
|
134
|
+
if (past.length > 0) await input.remove(past)
|
|
135
|
+
if (page.isDone) return
|
|
136
|
+
cursor = page.continueCursor
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** One pass over a workflow at `now`: its steps' runs, then its turn tasks, each as what it keeps says. */
|
|
141
|
+
const passOver = async (ctx: ActionCtx, input: { readonly workflow: string; readonly now: number }) => {
|
|
142
|
+
const graph = await ctx.runQuery(internal.retention.graphOf, { workflow: input.workflow })
|
|
143
|
+
if (graph === null) return { runs: 0, turnTasks: 0 }
|
|
144
|
+
const beforeOf = (days: number) => input.now - days * 24 * 60 * 60 * 1000
|
|
145
|
+
let runs = 0
|
|
146
|
+
let turnTasks = 0
|
|
147
|
+
for (const step of graph.steps.filter((candidate) => candidate.kind !== "workflow")) {
|
|
148
|
+
const keeps = retentionOf(graph, step.id)
|
|
149
|
+
const before = beforeOf(keeps.days)
|
|
150
|
+
await pastTheNewest({
|
|
151
|
+
page: (cursor) => ctx.runQuery(internal.retention.runsPage, { workflow: input.workflow, step: step.id, paginationOpts: { numItems: PAGE, cursor } }),
|
|
152
|
+
keep: keeps.keepAtLeastRuns,
|
|
153
|
+
qualifies: (run) => run.status !== "running" && run.endedAt !== null && run.endedAt < before,
|
|
154
|
+
remove: async (past) => {
|
|
155
|
+
runs += await ctx.runMutation(internal.retention.deleteRuns, { runs: past.map((run) => run.run), before })
|
|
156
|
+
},
|
|
157
|
+
})
|
|
158
|
+
}
|
|
159
|
+
const timers = new Set(graph.events.filter((event) => event.kind === "timer").map((event) => event.id))
|
|
160
|
+
if (timers.size > 0) {
|
|
161
|
+
const keeps = retentionOf(graph, null)
|
|
162
|
+
const before = beforeOf(keeps.days)
|
|
163
|
+
for (const end of graph.endStates) {
|
|
164
|
+
await pastTheNewest({
|
|
165
|
+
page: async (cursor) => {
|
|
166
|
+
const page = await ctx.runQuery(internal.retention.flowsPage, { workflow: input.workflow, place: `end:${end}`, paginationOpts: { numItems: PAGE, cursor } })
|
|
167
|
+
// Only turn tasks count towards the newest kept at their end state.
|
|
168
|
+
return { ...page, page: page.page.filter((flow) => timers.has(flow.startedBy)) }
|
|
169
|
+
},
|
|
170
|
+
keep: keeps.keepAtLeastRuns,
|
|
171
|
+
qualifies: (flow) => flow.enteredAt < before,
|
|
172
|
+
remove: async (past) => {
|
|
173
|
+
const gone = await ctx.runMutation(internal.retention.deleteTurnTasks, { workflow: input.workflow, tasks: past.map((flow) => flow.task) })
|
|
174
|
+
turnTasks += gone.tasks
|
|
175
|
+
runs += gone.runs
|
|
176
|
+
},
|
|
177
|
+
})
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return { runs, turnTasks }
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The daily pass, which schedules the next. */
|
|
184
|
+
export const scheduledPass = internalAction({
|
|
185
|
+
args: { workflow: v.string() },
|
|
186
|
+
returns: v.null(),
|
|
187
|
+
handler: async (ctx, args) => {
|
|
188
|
+
const at = Date.now()
|
|
189
|
+
const pass = await passOver(ctx, { workflow: args.workflow, now: at })
|
|
190
|
+
await ctx.runMutation(internal.retention.recordPass, { workflow: args.workflow, at, ...pass, scheduleNext: true })
|
|
191
|
+
return null
|
|
192
|
+
},
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
/** A pass now, or as if at `now`; the workforce exposes it, and tests pass a `now` days ahead. */
|
|
196
|
+
export const pruneNow = action({
|
|
197
|
+
args: { workflow: v.string(), now: v.optional(v.number()) },
|
|
198
|
+
returns: passValidator,
|
|
199
|
+
handler: async (ctx, args) => {
|
|
200
|
+
const at = args.now ?? Date.now()
|
|
201
|
+
const pass = await passOver(ctx, { workflow: args.workflow, now: at })
|
|
202
|
+
await ctx.runMutation(internal.retention.recordPass, { workflow: args.workflow, at, ...pass, scheduleNext: false })
|
|
203
|
+
return pass
|
|
204
|
+
},
|
|
205
|
+
})
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ConvexError } from "convex/values"
|
|
2
|
+
import { Cause, Effect, Exit, Option, pipe } from "effect"
|
|
3
|
+
import type { MutationCtx } from "./_generated/server"
|
|
4
|
+
import type { EngineError } from "./errors"
|
|
5
|
+
import { ConvexWorkflowStore, WorkflowStore } from "./store"
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The runtime boundary between a Convex mutation and the engine: runs one engine operation against this mutation's
|
|
9
|
+
* tables. An expected engine error becomes a ConvexError the caller can read (`data.tag`), and fails the whole
|
|
10
|
+
* transaction, so nothing the operation wrote is kept.
|
|
11
|
+
*/
|
|
12
|
+
export const runEngine = async <A>(ctx: MutationCtx, operation: Effect.fn.Return<A, EngineError, WorkflowStore>): Promise<A> => {
|
|
13
|
+
const exit = await Effect.runPromiseExit(
|
|
14
|
+
pipe(
|
|
15
|
+
Effect.gen(() => operation),
|
|
16
|
+
Effect.provideService(WorkflowStore, new ConvexWorkflowStore(ctx)),
|
|
17
|
+
),
|
|
18
|
+
)
|
|
19
|
+
if (Exit.isSuccess(exit)) return exit.value
|
|
20
|
+
const maybeError = Cause.findErrorOption(exit.cause)
|
|
21
|
+
if (Option.isSome(maybeError)) {
|
|
22
|
+
throw new ConvexError({ tag: maybeError.value._tag, message: maybeError.value.message })
|
|
23
|
+
}
|
|
24
|
+
throw new Error(Cause.pretty(exit.cause))
|
|
25
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { defineSchema, defineTable } from "convex/server"
|
|
2
|
+
import { v } from "convex/values"
|
|
3
|
+
import {
|
|
4
|
+
budgetsValidator,
|
|
5
|
+
graphValidator,
|
|
6
|
+
parentRefValidator,
|
|
7
|
+
stepSpendValidator,
|
|
8
|
+
stepUsedValidator,
|
|
9
|
+
skippedOtherValidator,
|
|
10
|
+
taskFileValidator,
|
|
11
|
+
workforceHooksValidator,
|
|
12
|
+
} from "../src/graph"
|
|
13
|
+
|
|
14
|
+
export const stepRunStatusValidator = v.union(v.literal("running"), v.literal("ended"), v.literal("failed"))
|
|
15
|
+
export const budgetNameValidator = v.union(v.literal("agents"), v.literal("cpu"), v.literal("none"))
|
|
16
|
+
|
|
17
|
+
export default defineSchema({
|
|
18
|
+
workflows: defineTable({
|
|
19
|
+
name: v.string(),
|
|
20
|
+
graph: graphValidator,
|
|
21
|
+
budgets: budgetsValidator,
|
|
22
|
+
/** The current registration's timer ticks carry this; a tick scheduled under another stops (`Engine.timerFired`). */
|
|
23
|
+
timerGeneration: v.number(),
|
|
24
|
+
/** The next retention pass (`retention.ts`), scheduled a day after the last; absent until the workflow is registered. */
|
|
25
|
+
pruning: v.optional(v.id("_scheduled_functions")),
|
|
26
|
+
/** What the last retention pass deleted, and when. */
|
|
27
|
+
lastPruned: v.optional(v.object({ at: v.number(), runs: v.number(), turnTasks: v.number() })),
|
|
28
|
+
/** Absent when the workflow runs outside a workforce, where it can have no sub-workflow steps. */
|
|
29
|
+
hooks: v.optional(workforceHooksValidator),
|
|
30
|
+
/** `versionOf` its current graph. */
|
|
31
|
+
version: v.string(),
|
|
32
|
+
}).index("by_name", ["name"]),
|
|
33
|
+
|
|
34
|
+
/** A task's data: its attribute fields (encoded by the workflow's task schema) and references to its files. */
|
|
35
|
+
tasks: defineTable({
|
|
36
|
+
workflow: v.string(),
|
|
37
|
+
fields: v.any(),
|
|
38
|
+
files: v.array(taskFileValidator),
|
|
39
|
+
/** Set on a task a sub-workflow step of another workflow created. */
|
|
40
|
+
parent: v.optional(parentRefValidator),
|
|
41
|
+
/** The end state the task's arrival flow reached and no step consumes, once it has. */
|
|
42
|
+
endedAs: v.optional(v.string()),
|
|
43
|
+
/**
|
|
44
|
+
* Set on a task a declared item list made: the list event and the item's key. `leftWhileEnded` marks one whose item
|
|
45
|
+
* left the list after the task ended, so its item's return sends it back to work.
|
|
46
|
+
*/
|
|
47
|
+
listedAs: v.optional(v.object({ event: v.string(), key: v.string(), leftWhileEnded: v.optional(v.boolean()) })),
|
|
48
|
+
})
|
|
49
|
+
.index("by_workflow", ["workflow"])
|
|
50
|
+
.index("by_listed", ["workflow", "listedAs.event", "listedAs.key"])
|
|
51
|
+
.index("by_parent_step", ["parent.workflow", "parent.step"]),
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* One task travelling through the workflow from one event. A task has one flow per event that started one:
|
|
55
|
+
* its arrival, and each change of a field a change event watches.
|
|
56
|
+
* `place` is `line:<line id>`, `step:<step id>` or `end:<end state>`; `enteredAt` orders each place's queue.
|
|
57
|
+
*/
|
|
58
|
+
flows: defineTable({
|
|
59
|
+
workflow: v.string(),
|
|
60
|
+
task: v.id("tasks"),
|
|
61
|
+
startedBy: v.string(),
|
|
62
|
+
place: v.string(),
|
|
63
|
+
enteredAt: v.number(),
|
|
64
|
+
/** A flow a failed run sent back waits until then before a worker may take it (the step's `retries.delayMs`). */
|
|
65
|
+
notBefore: v.optional(v.number()),
|
|
66
|
+
})
|
|
67
|
+
.index("by_workflow_place_entered", ["workflow", "place", "enteredAt"])
|
|
68
|
+
.index("by_task_started_by", ["task", "startedBy"]),
|
|
69
|
+
|
|
70
|
+
/** The record of one task in one step: who ran it, when, its outcome, and the budget unit it holds while running. */
|
|
71
|
+
stepRuns: defineTable({
|
|
72
|
+
workflow: v.string(),
|
|
73
|
+
task: v.id("tasks"),
|
|
74
|
+
flow: v.id("flows"),
|
|
75
|
+
step: v.string(),
|
|
76
|
+
budget: budgetNameValidator,
|
|
77
|
+
status: stepRunStatusValidator,
|
|
78
|
+
worker: v.optional(v.string()),
|
|
79
|
+
startedAt: v.number(),
|
|
80
|
+
takenFrom: v.object({ place: v.string(), enteredAt: v.number() }),
|
|
81
|
+
endedAt: v.optional(v.number()),
|
|
82
|
+
endState: v.optional(v.string()),
|
|
83
|
+
error: v.optional(v.string()),
|
|
84
|
+
/** The graph version (`versionOf`) the run ran under. */
|
|
85
|
+
version: v.string(),
|
|
86
|
+
/** Which try of this task in this step the run is, counting from 1. */
|
|
87
|
+
call: v.number(),
|
|
88
|
+
spend: stepSpendValidator,
|
|
89
|
+
used: stepUsedValidator,
|
|
90
|
+
agent: v.optional(v.string()),
|
|
91
|
+
files: v.array(v.string()),
|
|
92
|
+
/** The transcripts of the agent runs the step made. */
|
|
93
|
+
transcripts: v.array(taskFileValidator),
|
|
94
|
+
/** The fingerprint of the inputs the run read (`inputsChanged`). */
|
|
95
|
+
fingerprint: v.optional(v.string()),
|
|
96
|
+
/** What the step said about the task when it ended, such as why it matched or what blocked it. */
|
|
97
|
+
note: v.optional(v.string()),
|
|
98
|
+
/** Writes to other tasks the run made that were not applied, each with why (`StepOutcome.others`). */
|
|
99
|
+
skippedOthers: v.optional(v.array(skippedOtherValidator)),
|
|
100
|
+
})
|
|
101
|
+
.index("by_workflow_budget_status", ["workflow", "budget", "status"])
|
|
102
|
+
.index("by_flow_status", ["flow", "status"])
|
|
103
|
+
.index("by_task", ["task"])
|
|
104
|
+
.index("by_workflow_step_started", ["workflow", "step", "startedAt"]),
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* How long a worker holds a taken task without heartbeating. Kept apart from `stepRuns` so a heartbeat never writes a
|
|
108
|
+
* row that `take` reads to check budgets, which would make every concurrent take retry.
|
|
109
|
+
*/
|
|
110
|
+
leases: defineTable({ run: v.id("stepRuns"), expiresAt: v.number(), heartbeatAt: v.number() }).index("by_run", ["run"]),
|
|
111
|
+
|
|
112
|
+
/** What was said about a task outside its step runs: the reason a call sent it back. Notes from steps are on `stepRuns`. */
|
|
113
|
+
taskNotes: defineTable({
|
|
114
|
+
task: v.id("tasks"),
|
|
115
|
+
note: v.string(),
|
|
116
|
+
at: v.number(),
|
|
117
|
+
/** The step whose run said it, for a run's note kept here once retention deleted the run. */
|
|
118
|
+
step: v.optional(v.string()),
|
|
119
|
+
}).index("by_task", ["task"]),
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The tasks a flow waiting in a sub-workflow step is waiting on, one per list entry. They live in the sub-workflow's
|
|
123
|
+
* own component; `task` is its id there, once the workforce has created it.
|
|
124
|
+
*/
|
|
125
|
+
subWorkflowTasks: defineTable({
|
|
126
|
+
flow: v.id("flows"),
|
|
127
|
+
entryIndex: v.number(),
|
|
128
|
+
workflow: v.string(),
|
|
129
|
+
task: v.optional(v.string()),
|
|
130
|
+
endedAs: v.optional(v.string()),
|
|
131
|
+
}).index("by_flow_entry", ["flow", "entryIndex"]),
|
|
132
|
+
})
|