@jive-sh/workflow-platform 0.2.0 → 0.3.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 +31 -17
- package/dist/cpu-limit/limiter.js +54 -11
- package/dist/cpu-limit/limiter.js.map +1 -1
- package/dist/index.js +40 -47
- package/dist/index.js.map +1 -1
- package/dist/keep-running.js +5 -5
- package/dist/keep-running.js.map +1 -1
- package/dist/pick-wakes.js +7 -1
- package/dist/pick-wakes.js.map +1 -1
- package/dist/queue-counts.js +47 -0
- package/dist/queue-counts.js.map +1 -0
- package/dist/steps.js +35 -15
- package/dist/steps.js.map +1 -1
- package/dist/storage/budgets.js +14 -0
- package/dist/storage/budgets.js.map +1 -1
- package/dist/storage/sqlite-store.js +36 -16
- package/dist/storage/sqlite-store.js.map +1 -1
- package/dist/views/workflows-view.js +76 -61
- package/dist/views/workflows-view.js.map +1 -1
- package/package.json +1 -1
- package/src/cpu-limit/limiter.ts +61 -11
- package/src/dashboard/dashboard.css +78 -0
- package/src/dashboard/index.tsx +3 -0
- package/src/dashboard/queue-chart.tsx +137 -0
- package/src/dashboard/step-graph.tsx +98 -0
- package/src/dashboard/workflow-dag.tsx +256 -0
- package/src/dashboard/workflows-dashboard.tsx +313 -0
- package/src/index.ts +43 -48
- package/src/keep-running.ts +5 -7
- package/src/pick-wakes.ts +9 -2
- package/src/queue-counts.ts +61 -0
- package/src/steps.ts +35 -23
- package/src/storage/budgets.ts +13 -0
- package/src/storage/sqlite-store.ts +41 -18
- package/src/storage/step-records.ts +6 -5
- package/src/views/workflows-view.ts +120 -89
package/src/steps.ts
CHANGED
|
@@ -265,6 +265,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
265
265
|
/** This process, to tell its own records from another's. */
|
|
266
266
|
readonly thisProcess: () => ProcessIdentity;
|
|
267
267
|
readonly inputs: InputRecords;
|
|
268
|
+
/** A workflow's queue changed with no wake of its Picks: one of them claimed an item (`queue-counts.ts`). */
|
|
269
|
+
readonly queueChanged: (workflow: string) => void;
|
|
268
270
|
}) => {
|
|
269
271
|
const { stepRecords: records, stepFiles } = deps;
|
|
270
272
|
type Declaration = WorkflowDeclaration<Phase, R>;
|
|
@@ -333,12 +335,21 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
333
335
|
* Whether this run should stand down before its next agent call, and whether its Pick, finding nothing it can claim, waits
|
|
334
336
|
* for work rather than ending its run. A test supplies others.
|
|
335
337
|
*/
|
|
336
|
-
/**
|
|
337
|
-
|
|
338
|
+
/**
|
|
339
|
+
* A declared workflow's limits: its run limit (`runLimitOf`, none for no limit), and its agents' limit where its budget
|
|
340
|
+
* keeps it going (none for any other). None for one not declared, or with no store to read.
|
|
341
|
+
*/
|
|
342
|
+
const limitsOf = (workflow: string): Effect.Effect<{ readonly runs: number | null; readonly agents: number | null } | null, StorageError> => {
|
|
338
343
|
const d = DECLARED.get(workflow);
|
|
339
|
-
if (d === undefined
|
|
340
|
-
return Effect.map(deps.budgets.limitsOf(workflow), (limits) => (limits === null ? null : {
|
|
344
|
+
if (d === undefined) return Effect.succeed(null);
|
|
345
|
+
return Effect.map(deps.budgets.limitsOf(workflow), (limits) => (limits === null ? null : { runs: runLimitOf(d, limits), agents: keptRunningByItsBudget(d) ? limits.agents : null }));
|
|
341
346
|
};
|
|
347
|
+
/** Whether a run is past the runs its workflow's run limit keeps, oldest first; never where it has no run limit. */
|
|
348
|
+
const pastItsRunLimit = (workflow: string, run: string): Effect.Effect<boolean, StorageError> =>
|
|
349
|
+
Effect.flatMap(limitsOf(workflow), (w) => {
|
|
350
|
+
const runs = w === null ? null : w.runs;
|
|
351
|
+
return runs === null ? Effect.succeed(false) : Effect.map(runsOldestFirst([workflow]), (going) => surplusRun(going, run, runs));
|
|
352
|
+
});
|
|
342
353
|
|
|
343
354
|
/**
|
|
344
355
|
* LIMITS THAT CANNOT BE READ HOLD THE RUN WHERE IT IS: it does not stand down, its Pick waits, and its agent step waits for a
|
|
@@ -351,27 +362,20 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
351
362
|
defaultValue: () => ({
|
|
352
363
|
// Among its workflow's unfinished runs, oldest first, the run is past those its run limit keeps (`runLimit`). A run not
|
|
353
364
|
// listed is not counted.
|
|
354
|
-
standsDown: (workflow, run) => pipe(
|
|
355
|
-
|
|
356
|
-
Effect.flatMap((w) => (w === null ? Effect.succeed(false) : Effect.map(runsOldestFirst([workflow]), (going) => surplusRun(going, run, runLimit(w.limits))))),
|
|
357
|
-
Effect.catchTag('StorageError', unreadLimits(workflow, () => false)),
|
|
358
|
-
),
|
|
359
|
-
waitsForWork: (workflow, run) => pipe(
|
|
360
|
-
limitsOf(workflow),
|
|
361
|
-
Effect.flatMap((w) => (w === null ? Effect.succeed(true) : Effect.map(runsOldestFirst([workflow]), (going) => !surplusRun(going, run, runLimit(w.limits))))),
|
|
362
|
-
Effect.catchTag('StorageError', unreadLimits(workflow, () => true)),
|
|
363
|
-
),
|
|
365
|
+
standsDown: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.catchTag('StorageError', unreadLimits(workflow, () => false))),
|
|
366
|
+
waitsForWork: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.map((past) => !past), Effect.catchTag('StorageError', unreadLimits(workflow, () => true))),
|
|
364
367
|
// Its other runs in an agent step, a waiting one not counted, against its agents' limit: at 0 none is ever free, and its
|
|
365
368
|
// runs wait at their first agent step until the limit is raised.
|
|
366
369
|
agentSlot: (workflow, run) => pipe(
|
|
367
370
|
limitsOf(workflow),
|
|
368
371
|
Effect.flatMap((w): Effect.Effect<{ readonly free: true } | { readonly free: false; readonly why: string }, StorageError> => {
|
|
369
|
-
|
|
370
|
-
if (
|
|
372
|
+
const agents = w === null ? null : w.agents;
|
|
373
|
+
if (agents === null) return Effect.succeed({ free: true });
|
|
374
|
+
if (agents === 0) return Effect.succeed({ free: false, why: 'waits for an agent: its agents\x27 limit is 0' });
|
|
371
375
|
return Effect.map(Effect.all({ runs: runsOldestFirst([workflow]), inAgentStep: records.runsInAgentStep(workflow) }), ({ runs, inAgentStep }) => {
|
|
372
376
|
const going = new Set(runs);
|
|
373
377
|
const busy = inAgentStep.filter((r) => r !== run && going.has(r)).length;
|
|
374
|
-
return busy <
|
|
378
|
+
return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use` };
|
|
375
379
|
});
|
|
376
380
|
}),
|
|
377
381
|
Effect.catchTag('StorageError', unreadLimits(workflow, (why) => ({ free: false as const, why: `waits for an agent: its limits could not be read (${why})` }))),
|
|
@@ -528,13 +532,20 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
528
532
|
return snapshot === null ? { restored: [], conflicts: [] } : stepFiles.undoFiles(snapshot, attributed ?? []);
|
|
529
533
|
}));
|
|
530
534
|
|
|
531
|
-
/**
|
|
532
|
-
|
|
533
|
-
|
|
535
|
+
/**
|
|
536
|
+
* A RUN PAST ITS WORKFLOW'S RUN LIMIT ENDS BEFORE IT TAKES ON MORE WORK, inside the step's activity: before a Pick, before
|
|
537
|
+
* an agent step, and before the first step this process runs of it (a run the engine resumed after a restart). It fails
|
|
538
|
+
* with `STOOD_DOWN`. A step between those goes on, so what an agent step just made is still checked and recorded. At a run
|
|
539
|
+
* limit of 0 every run is past it, so each run already going ends at the next of those.
|
|
540
|
+
*/
|
|
541
|
+
const standDownIfSurplus = (step: { readonly agent: boolean; readonly picks: boolean }) => Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => {
|
|
542
|
+
if (!step.agent && !step.picks && lastStepRan.has(instance.executionId)) return Effect.void;
|
|
543
|
+
return Effect.flatMap(AgentBudgets, (budgets) => Effect.flatMap(budgets.standsDown(instance.workflow._tag, instance.executionId), (surplus) => {
|
|
534
544
|
if (!surplus) return Effect.void;
|
|
535
|
-
console.log(`[
|
|
545
|
+
console.log(`[run limit] ${instance.workflow._tag} run ${instance.executionId} stood down: its workflow has more runs going than its run limit`);
|
|
536
546
|
return Effect.fail(STOOD_DOWN);
|
|
537
|
-
}))
|
|
547
|
+
}));
|
|
548
|
+
});
|
|
538
549
|
|
|
539
550
|
/** One run of a workflow picks at a time: its choice is on its step record before the next reads what is taken. */
|
|
540
551
|
const pickingOneAtATime = <A, E, R2>(workflow: string, pick: Effect.Effect<A, E, R2>): Effect.Effect<A, E, R2> => {
|
|
@@ -570,6 +581,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
570
581
|
const found = yield* pickingOneAtATime(workflow, pick);
|
|
571
582
|
if (waited) deps.wakes.countRePick(workflow, performance.now() - began);
|
|
572
583
|
if (picked(found) || !(yield* budgets.waitsForWork(workflow, instance.executionId))) {
|
|
584
|
+
if (picked(found)) deps.queueChanged(workflow);
|
|
573
585
|
if (waited && record !== null) {
|
|
574
586
|
yield* recorded('end its wait', records.setStepWaiting({ id: record, waiting: null }));
|
|
575
587
|
yield* recorded('start its record again', records.restartStepRun(record));
|
|
@@ -627,7 +639,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
627
639
|
success: d.success,
|
|
628
640
|
error: Schema.String,
|
|
629
641
|
execute: pipe(
|
|
630
|
-
d.agent
|
|
642
|
+
standDownIfSurplus({ agent: d.agent, picks: d.picked !== undefined }),
|
|
631
643
|
Effect.andThen(measured(declaration, options?.call ?? null, options?.subject ?? null, d.subject, d.reason, d.mayWrite, d.picked === undefined ? execute : untilPicked(d.picked, execute))),
|
|
632
644
|
Effect.retry({ while: deps.isTransientFailure, times: 10, schedule: Schedule.spaced('3 seconds') }),
|
|
633
645
|
Effect.mapError(describeFailure),
|
package/src/storage/budgets.ts
CHANGED
|
@@ -44,6 +44,8 @@ export interface WorkflowLimits {
|
|
|
44
44
|
export interface LimitStore {
|
|
45
45
|
/** A workflow's limits: 0 agents with none stored, and none where there is no store to read (a test). */
|
|
46
46
|
readonly limitsOf: (workflow: string) => Effect.Effect<WorkflowLimits | null, StorageError>;
|
|
47
|
+
/** Every stored workflow's limits, by name, in one read: one with none stored is absent. None where there is no store. */
|
|
48
|
+
readonly storedLimits: () => Effect.Effect<ReadonlyMap<string, WorkflowLimits> | null, StorageError>;
|
|
47
49
|
}
|
|
48
50
|
|
|
49
51
|
/**
|
|
@@ -65,4 +67,15 @@ export const sqliteBudgets = (options: { readonly file: () => string }): LimitSt
|
|
|
65
67
|
db.close();
|
|
66
68
|
}
|
|
67
69
|
}),
|
|
70
|
+
storedLimits: () => storeCall('limits: storedLimits', () => {
|
|
71
|
+
const file = options.file();
|
|
72
|
+
if (!fs.existsSync(file)) return null;
|
|
73
|
+
const db = new Database(file, { readonly: true });
|
|
74
|
+
try {
|
|
75
|
+
if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'workflow_budgets'`).get() === null) return null;
|
|
76
|
+
return new Map((db.query(WORKFLOW_BUDGETS_SQL).all() as ReadonlyArray<WorkflowBudgetRow>).map((r) => [r.workflow, { agents: r.budget, runs: r.runs }]));
|
|
77
|
+
} finally {
|
|
78
|
+
db.close();
|
|
79
|
+
}
|
|
80
|
+
}),
|
|
68
81
|
});
|
|
@@ -47,7 +47,8 @@ CREATE TABLE IF NOT EXISTS cleared_but_listed (
|
|
|
47
47
|
);
|
|
48
48
|
CREATE INDEX IF NOT EXISTS step_runs_by_start ON step_runs (started);
|
|
49
49
|
CREATE INDEX IF NOT EXISTS step_runs_open ON step_runs (beat) WHERE ended IS NULL AND agent = 1;
|
|
50
|
-
CREATE INDEX IF NOT EXISTS step_runs_by_run ON step_runs (run, id)
|
|
50
|
+
CREATE INDEX IF NOT EXISTS step_runs_by_run ON step_runs (run, id);
|
|
51
|
+
CREATE INDEX IF NOT EXISTS step_runs_by_workflow ON step_runs (workflow, started);`;
|
|
51
52
|
|
|
52
53
|
/**
|
|
53
54
|
* TASKS AND THEIR NOTES (`tasks.ts`): one row per task, a workflow and its item, and its notes, which nothing updates or
|
|
@@ -147,7 +148,7 @@ CREATE INDEX IF NOT EXISTS input_runs_by_workflow ON input_runs (workflow, at);`
|
|
|
147
148
|
|
|
148
149
|
/**
|
|
149
150
|
* EACH QUEUE'S COUNTS OVER TIME: a row where a workflow's tasks in one bucket changed, so a dashboard draws its history.
|
|
150
|
-
* Written
|
|
151
|
+
* Written when a queue may have changed (`queue-counts.ts`), only where a count moved.
|
|
151
152
|
*/
|
|
152
153
|
const QUEUE_COUNTS_SCHEMA = `
|
|
153
154
|
CREATE TABLE IF NOT EXISTS queue_counts (
|
|
@@ -159,6 +160,16 @@ CREATE TABLE IF NOT EXISTS queue_counts (
|
|
|
159
160
|
);
|
|
160
161
|
CREATE INDEX IF NOT EXISTS queue_counts_by_at ON queue_counts (at);`;
|
|
161
162
|
|
|
163
|
+
/**
|
|
164
|
+
* Whether a records file has the schema this code reads: every table and index the newest change to it added. A project
|
|
165
|
+
* that applies the schema only when it must (a write takes the lock) asks this first.
|
|
166
|
+
*/
|
|
167
|
+
export const stepRecordsSchemaApplied = (db: Database): boolean => {
|
|
168
|
+
const newest = ['step_runs', 'queue_counts', 'step_runs_by_workflow'];
|
|
169
|
+
const present = new Set((db.query('SELECT name FROM sqlite_master').all() as Array<{ name: string }>).map((r) => r.name));
|
|
170
|
+
return newest.every((name) => present.has(name));
|
|
171
|
+
};
|
|
172
|
+
|
|
162
173
|
/** Brings a records file up to the schema this code reads, as a writer or a first reader finds it. */
|
|
163
174
|
export const applyStepRecordsSchema = (db: Database): void => {
|
|
164
175
|
db.exec(STEP_RUNS_SCHEMA);
|
|
@@ -390,6 +401,18 @@ export const sqliteStore = (options: {
|
|
|
390
401
|
}
|
|
391
402
|
};
|
|
392
403
|
|
|
404
|
+
/**
|
|
405
|
+
* The runs whose first step started at or after `?1`, one workflow's (`?2`) where it is named: those with a record in the
|
|
406
|
+
* window and none before it, read by the records' start (`step_runs_by_start`, `step_runs_by_workflow`) and each run's
|
|
407
|
+
* own (`step_runs_by_run`). Grouping every record by run to find each one's first read the whole table: 0.5 s at 166,000
|
|
408
|
+
* records, in each of the five readings that used it (2026-11-17).
|
|
409
|
+
*/
|
|
410
|
+
const runsBegunSince = (workflow: string | undefined): string =>
|
|
411
|
+
`SELECT DISTINCT b.run FROM step_runs b WHERE b.started >= ?1 ${workflow === undefined ? '' : 'AND b.workflow = ?2'}
|
|
412
|
+
AND NOT EXISTS (SELECT 1 FROM step_runs e WHERE e.run = b.run AND e.started < ?1)`;
|
|
413
|
+
/** The parameters of a reading over a window, one workflow's where it is named. */
|
|
414
|
+
const windowOf = (since: number, workflow: string | undefined): ReadonlyArray<number | string> => (workflow === undefined ? [since] : [since, workflow]);
|
|
415
|
+
|
|
393
416
|
const stepRecords: StepRecords = storeCalls<StepRecords>('step records', {
|
|
394
417
|
openStepRun: (r) => tryWrite((db) => {
|
|
395
418
|
const now = Date.now() / 1000;
|
|
@@ -484,24 +507,24 @@ export const sqliteStore = (options: {
|
|
|
484
507
|
const r = db.query('SELECT MAX(MAX(started, beat, COALESCE(ended, 0))) AS active, MAX(ended) AS ended FROM step_runs WHERE workflow = ?').get(workflow) as { active: number | null; ended: number | null };
|
|
485
508
|
return { activeAt: r.active, endedAt: r.ended };
|
|
486
509
|
}, { activeAt: null, endedAt: null }),
|
|
487
|
-
runCostsSince: (since) =>
|
|
510
|
+
runCostsSince: (since, workflow) =>
|
|
488
511
|
read((db) => (db.query(
|
|
489
512
|
`SELECT workflow, run, MIN(started) AS started, MAX(COALESCE(ended, beat)) - MIN(started) AS seconds,
|
|
490
513
|
SUM(fresh + cache_write + cache_read + output) AS tokens, COALESCE(SUM(cpu_seconds), 0) AS cpuSeconds,
|
|
491
514
|
COALESCE(SUM(child_cpu_seconds), 0) AS childCpuSeconds, SUM(compiles) AS compiles, COALESCE(MAX(peak_memory_mb), 0) AS peakMemoryMb,
|
|
492
515
|
SUM(ended IS NULL) > 0 AS going
|
|
493
|
-
FROM step_runs WHERE run IN (
|
|
516
|
+
FROM step_runs WHERE run IN (${runsBegunSince(workflow)})
|
|
494
517
|
GROUP BY workflow, run ORDER BY started`,
|
|
495
|
-
).all(since) as ReadonlyArray<Omit<RunCost, 'going'> & { going: number }>).map((r) => ({ ...r, going: r.going === 1 })), []),
|
|
496
|
-
stepRunsSince: (since) =>
|
|
518
|
+
).all(...windowOf(since, workflow)) as ReadonlyArray<Omit<RunCost, 'going'> & { going: number }>).map((r) => ({ ...r, going: r.going === 1 })), []),
|
|
519
|
+
stepRunsSince: (since, workflow) =>
|
|
497
520
|
read((db) => db.query(
|
|
498
521
|
`SELECT workflow, run, step, MAX(agent) AS agent, COUNT(*) AS calls, COALESCE(SUM(ended IS NULL), 0) AS open,
|
|
499
522
|
COALESCE(SUM(outcome = 'failure'), 0) AS failed, COALESCE(SUM((ended - started) * 1000), 0) AS ms,
|
|
500
523
|
SUM(fresh) AS fresh, SUM(cache_write) AS cache_write, SUM(cache_read) AS cache_read, SUM(output) AS output, SUM(compiles) AS compiles, subject, SUM(requests) AS requests,
|
|
501
524
|
COALESCE(SUM(cpu_seconds), 0) AS cpu_seconds, COALESCE(SUM(files_written), 0) AS files_written, COALESCE(MAX(peak_memory_mb), 0) AS peak_memory_mb,
|
|
502
525
|
MIN(CASE WHEN ended IS NULL AND agent = 1 AND requests = 0 AND fresh + cache_write + cache_read = 0 AND beat >= ?2 AND waiting IS NULL THEN started END) AS no_usage_since
|
|
503
|
-
FROM step_runs WHERE started >= ?1 GROUP BY workflow, run, step, subject`,
|
|
504
|
-
).all(since, Date.now() / 1000 - AGENT_LIVE_SECONDS) as ReadonlyArray<StepRunRow>, []),
|
|
526
|
+
FROM step_runs WHERE started >= ?1 ${workflow === undefined ? '' : 'AND workflow = ?3'} GROUP BY workflow, run, step, subject`,
|
|
527
|
+
).all(since, Date.now() / 1000 - AGENT_LIVE_SECONDS, ...(workflow === undefined ? [] : [workflow])) as ReadonlyArray<StepRunRow>, []),
|
|
505
528
|
agentModelsSince: (since) =>
|
|
506
529
|
read((db) => db.query('SELECT model, COUNT(*) AS steps FROM step_runs WHERE started >= ? AND model IS NOT NULL GROUP BY model').all(since) as ReadonlyArray<{ model: string; steps: number }>, []),
|
|
507
530
|
stepRunsBegin: () =>
|
|
@@ -511,8 +534,8 @@ export const sqliteStore = (options: {
|
|
|
511
534
|
`SELECT workflow, run, MIN(started) AS started, SUM(fresh) AS fresh, SUM(cache_write) AS cacheWrite, SUM(cache_read) AS cacheRead, SUM(output) AS output, SUM(requests) AS requests
|
|
512
535
|
FROM step_runs WHERE agent = 1 GROUP BY workflow, run`,
|
|
513
536
|
).all() as ReadonlyArray<{ workflow: string; run: string; started: number; fresh: number; cacheWrite: number; cacheRead: number; output: number; requests: number }>, []),
|
|
514
|
-
runOutcomesSince: (since) =>
|
|
515
|
-
read((db) => db.query(
|
|
537
|
+
runOutcomesSince: (since, workflow) =>
|
|
538
|
+
read((db) => db.query(`SELECT workflow, run, subject, outcome, finished, at FROM run_outcomes WHERE at >= ?1 ${workflow === undefined ? '' : 'AND workflow = ?2'}`).all(...windowOf(since, workflow)) as ReadonlyArray<RunOutcomeRow>, []),
|
|
516
539
|
undeclaredWritesSince: (since) =>
|
|
517
540
|
read((db) => db.query('SELECT hour, folder, files FROM undeclared_writes WHERE hour >= ? ORDER BY hour').all(since) as ReadonlyArray<UndeclaredWrites>, []),
|
|
518
541
|
itemCosts: ({ workflow, step, since, rank = 'tokens' }) =>
|
|
@@ -563,12 +586,12 @@ export const sqliteStore = (options: {
|
|
|
563
586
|
FROM step_runs s JOIN (SELECT value AS run FROM json_each(?1)) w ON w.run = s.run
|
|
564
587
|
WHERE s.id = (SELECT MAX(id) FROM step_runs n WHERE n.run = s.run)`,
|
|
565
588
|
).all(JSON.stringify(runs)) as ReadonlyArray<NewestStepRecord>, []),
|
|
566
|
-
funnelRecordsSince: (since) =>
|
|
589
|
+
funnelRecordsSince: (since, workflow) =>
|
|
567
590
|
read((db) => {
|
|
568
|
-
const inWindow =
|
|
591
|
+
const inWindow = runsBegunSince(workflow);
|
|
569
592
|
return {
|
|
570
|
-
records: db.query(`SELECT workflow, run, step, agent, started, ended, outcome, reason, error, scope FROM step_runs WHERE run IN (${inWindow}) ORDER BY id`).all(since) as ReadonlyArray<FunnelStepRecord>,
|
|
571
|
-
outcomes: db.query(`SELECT workflow, run, subject, outcome, finished, at FROM run_outcomes WHERE run IN (${inWindow})`).all(since) as ReadonlyArray<RunOutcomeRow>,
|
|
593
|
+
records: db.query(`SELECT workflow, run, step, agent, started, ended, outcome, reason, error, scope FROM step_runs WHERE run IN (${inWindow}) ORDER BY id`).all(...windowOf(since, workflow)) as ReadonlyArray<FunnelStepRecord>,
|
|
594
|
+
outcomes: db.query(`SELECT workflow, run, subject, outcome, finished, at FROM run_outcomes WHERE run IN (${inWindow})`).all(...windowOf(since, workflow)) as ReadonlyArray<RunOutcomeRow>,
|
|
572
595
|
};
|
|
573
596
|
}, { records: [], outcomes: [] }),
|
|
574
597
|
newestCallsByItem: (r) =>
|
|
@@ -578,19 +601,19 @@ export const sqliteStore = (options: {
|
|
|
578
601
|
AND id = (SELECT MAX(t.id) FROM step_runs t WHERE t.workflow = ?1 AND lower(t.subject) = lower(s.subject) AND t.step IN (SELECT value FROM json_each(?2)) AND t.outcome = 'success')
|
|
579
602
|
ORDER BY ended DESC`,
|
|
580
603
|
).all(r.workflow, JSON.stringify(r.steps)) as ReadonlyArray<{ subject: string; run: string; activity: string; ended: number }>, []),
|
|
581
|
-
stepEdgesSince: (since) =>
|
|
604
|
+
stepEdgesSince: (since, workflow) =>
|
|
582
605
|
read((db) => {
|
|
583
606
|
const moves = `WITH r AS (
|
|
584
607
|
SELECT id, workflow, run, step, started, outcome FROM step_runs
|
|
585
|
-
WHERE run IN (SELECT DISTINCT run FROM step_runs WHERE started >= ?1) AND COALESCE(outcome, '') != 'interrupted'),
|
|
608
|
+
WHERE run IN (SELECT DISTINCT run FROM step_runs WHERE started >= ?1 ${workflow === undefined ? '' : 'AND workflow = ?2'}) AND COALESCE(outcome, '') != 'interrupted'),
|
|
586
609
|
t AS (SELECT workflow, run, step, started, outcome,
|
|
587
610
|
LAG(step) OVER w AS prev, LAG(outcome) OVER w AS prev_outcome, LEAD(step) OVER w AS next
|
|
588
611
|
FROM r WINDOW w AS (PARTITION BY run ORDER BY id))`;
|
|
589
612
|
const edges = (db.query(`${moves} SELECT workflow, prev AS "from", COALESCE(prev_outcome = 'failure', 0) AS fromFailed, step AS "to", COUNT(*) AS runs
|
|
590
|
-
FROM t WHERE started >= ?1 GROUP BY 1, 2, 3, 4`).all(since) as ReadonlyArray<Omit<StepEdgeTaken, 'fromFailed'> & { fromFailed: number }>)
|
|
613
|
+
FROM t WHERE started >= ?1 GROUP BY 1, 2, 3, 4`).all(...windowOf(since, workflow)) as ReadonlyArray<Omit<StepEdgeTaken, 'fromFailed'> & { fromFailed: number }>)
|
|
591
614
|
.map((e) => ({ ...e, fromFailed: e.fromFailed === 1 }));
|
|
592
615
|
const lasts = (db.query(`${moves} SELECT workflow, run, step, COALESCE(outcome = 'failure', 0) AS failed FROM t WHERE next IS NULL`)
|
|
593
|
-
.all(since) as ReadonlyArray<Omit<LastStepNow, 'failed'> & { failed: number }>).map((l) => ({ ...l, failed: l.failed === 1 }));
|
|
616
|
+
.all(...windowOf(since, workflow)) as ReadonlyArray<Omit<LastStepNow, 'failed'> & { failed: number }>).map((l) => ({ ...l, failed: l.failed === 1 }));
|
|
594
617
|
return { edges, lasts };
|
|
595
618
|
}, { edges: [], lasts: [] }),
|
|
596
619
|
});
|
|
@@ -262,15 +262,16 @@ export interface StepRecords {
|
|
|
262
262
|
readonly newestRun: (workflow: string) => Effect.Effect<{ readonly endedAt: number; readonly spent: boolean } | null, StorageError>;
|
|
263
263
|
/** A workflow's newest step activity (a start, heartbeat or end) and newest step end. */
|
|
264
264
|
readonly newestStepActivity: (workflow: string) => Effect.Effect<{ readonly activeAt: number | null; readonly endedAt: number | null }, StorageError>;
|
|
265
|
-
|
|
265
|
+
/** Each run's records since `since`, added up by step and subject. With `workflow`, here and below, only that workflow's. */
|
|
266
|
+
readonly stepRunsSince: (since: number, workflow?: string) => Effect.Effect<ReadonlyArray<StepRunRow>, StorageError>;
|
|
266
267
|
/** What each run that began since `since` cost, all its steps added up, its processes' CPU included. */
|
|
267
|
-
readonly runCostsSince: (since: number) => Effect.Effect<ReadonlyArray<RunCost>, StorageError>;
|
|
268
|
+
readonly runCostsSince: (since: number, workflow?: string) => Effect.Effect<ReadonlyArray<RunCost>, StorageError>;
|
|
268
269
|
readonly agentModelsSince: (since: number) => Effect.Effect<ReadonlyArray<{ readonly model: string; readonly steps: number }>, StorageError>;
|
|
269
270
|
/** When records begin; none before the first. */
|
|
270
271
|
readonly stepRunsBegin: () => Effect.Effect<number | null, StorageError>;
|
|
271
272
|
/** Every run with an agent step, all time: when it started and what its agent steps spent. */
|
|
272
273
|
readonly agentRunsEver: () => Effect.Effect<ReadonlyArray<{ readonly workflow: string; readonly run: string; readonly started: number; readonly fresh: number; readonly cacheWrite: number; readonly cacheRead: number; readonly output: number; readonly requests: number }>, StorageError>;
|
|
273
|
-
readonly runOutcomesSince: (since: number) => Effect.Effect<ReadonlyArray<RunOutcomeRow>, StorageError>;
|
|
274
|
+
readonly runOutcomesSince: (since: number, workflow?: string) => Effect.Effect<ReadonlyArray<RunOutcomeRow>, StorageError>;
|
|
274
275
|
readonly undeclaredWritesSince: (since: number) => Effect.Effect<ReadonlyArray<UndeclaredWrites>, StorageError>;
|
|
275
276
|
readonly itemCosts: (r: { readonly workflow: string; readonly step: string | null; readonly since: number; readonly rank?: ItemRank }) => Effect.Effect<ReadonlyArray<ItemCost>, StorageError>;
|
|
276
277
|
/** What a workflow's steps declared as shared cost since `since`: charged to no item. */
|
|
@@ -284,9 +285,9 @@ export interface StepRecords {
|
|
|
284
285
|
/** The newest record of each run named. */
|
|
285
286
|
readonly newestStepRecords: (runs: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<NewestStepRecord>, StorageError>;
|
|
286
287
|
/** Every record of every run whose first step started at or after `since`, and those runs' item outcomes. */
|
|
287
|
-
readonly funnelRecordsSince: (since: number) => Effect.Effect<{ readonly records: ReadonlyArray<FunnelStepRecord>; readonly outcomes: ReadonlyArray<RunOutcomeRow> }, StorageError>;
|
|
288
|
+
readonly funnelRecordsSince: (since: number, workflow?: string) => Effect.Effect<{ readonly records: ReadonlyArray<FunnelStepRecord>; readonly outcomes: ReadonlyArray<RunOutcomeRow> }, StorageError>;
|
|
288
289
|
/** Each item's newest successful call of these steps of a workflow, newest first. */
|
|
289
290
|
readonly newestCallsByItem: (r: { readonly workflow: string; readonly steps: ReadonlyArray<string> }) => Effect.Effect<ReadonlyArray<{ readonly subject: string; readonly run: string; readonly activity: string; readonly ended: number }>, StorageError>;
|
|
290
291
|
/** Every step-to-step move in the window, by workflow, and each run's last step. Interrupted records are not moves. */
|
|
291
|
-
readonly stepEdgesSince: (since: number) => Effect.Effect<{ readonly edges: ReadonlyArray<StepEdgeTaken>; readonly lasts: ReadonlyArray<LastStepNow> }, StorageError>;
|
|
292
|
+
readonly stepEdgesSince: (since: number, workflow?: string) => Effect.Effect<{ readonly edges: ReadonlyArray<StepEdgeTaken>; readonly lasts: ReadonlyArray<LastStepNow> }, StorageError>;
|
|
292
293
|
}
|
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* its limits
|
|
5
|
-
*
|
|
2
|
+
* A PROJECT'S WORKFLOWS AS ITS DASHBOARD SHOWS THEM, READ FROM THE RECORDS AT EACH REQUEST, in two readings:
|
|
3
|
+
*
|
|
4
|
+
* every workflow what it is, its limits, its queue's buckets and their history, and where work goes between workflows
|
|
5
|
+
* (`buildWorkflowsView`): what a page shows before a workflow is opened, a few small readings.
|
|
6
|
+
* one workflow its steps and their cost over a window, its step graph with the window's runs on it, and where its
|
|
7
|
+
* runs stopped and why (`buildWorkflowFigures`): read from its own records when a page opens it.
|
|
8
|
+
*
|
|
9
|
+
* Built whole and stored by a job every 5 minutes, the two were one view: 5.7 s of reading on a busy machine, 4.4 s of it
|
|
10
|
+
* three scans of every step record for figures only an opened workflow shows, and a page up to 5 minutes old (2026-11-17).
|
|
11
|
+
* Built from the declarations and the stores alone, so any project's workflows read the same; a project adds its own
|
|
12
|
+
* panels beside it. Where its runs are now (`runs-now.ts`) is read at each request too.
|
|
6
13
|
*/
|
|
7
14
|
import type { SourceRef, StepDeclaration, WorkflowDeclaration } from '../steps';
|
|
8
15
|
|
|
@@ -14,7 +21,7 @@ import { Effect } from 'effect';
|
|
|
14
21
|
import type { StorageError } from '../storage/storage-error';
|
|
15
22
|
import type { EngineRecords } from '../storage/engine-records';
|
|
16
23
|
import type { FunnelStepRecord, RunCost, RunOutcomeRow, StepRecords, StepRunRow } from '../storage/step-records';
|
|
17
|
-
import {
|
|
24
|
+
import { BUCKETS, type Bucket } from '../tasks';
|
|
18
25
|
import type { QueueCount, TaskStore } from '../storage/task-store';
|
|
19
26
|
import { stepFunnel, type StepFunnel } from './step-funnel';
|
|
20
27
|
import { workflowGraphs, type WorkflowGraph } from './step-graph';
|
|
@@ -137,6 +144,7 @@ export const yieldOf = (r: { readonly runs: number; readonly finished: number; r
|
|
|
137
144
|
perCompile: r.compiles === 0 ? null : r.finished / r.compiles,
|
|
138
145
|
});
|
|
139
146
|
|
|
147
|
+
/** A workflow as a page shows it before it is opened: what it is, its limits, its queue, and its place among the others. */
|
|
140
148
|
export interface WorkflowView {
|
|
141
149
|
readonly name: string;
|
|
142
150
|
readonly phase: string;
|
|
@@ -152,18 +160,7 @@ export interface WorkflowView {
|
|
|
152
160
|
* any other). None where no store is read.
|
|
153
161
|
*/
|
|
154
162
|
readonly limits: { readonly agents: number | null; readonly runs: number | null; readonly runsSet: boolean } | null;
|
|
155
|
-
/**
|
|
156
|
-
readonly paused: string | null;
|
|
157
|
-
readonly steps: ReadonlyArray<StepView>;
|
|
158
|
-
/** Its steps' costs added up. */
|
|
159
|
-
readonly total: StepCost;
|
|
160
|
-
readonly graph: WorkflowGraph;
|
|
161
|
-
readonly funnel: StepFunnel;
|
|
162
|
-
/** What a run of it costs, its processes included. */
|
|
163
|
-
readonly runCosts: RunCosts;
|
|
164
|
-
/** What its runs gave in the window, and in the window before it: the trend. */
|
|
165
|
-
readonly yields: { readonly now: Yield; readonly before: Yield };
|
|
166
|
-
/** Its tasks by bucket; none for a workflow with no item. */
|
|
163
|
+
/** Its tasks by bucket, as last counted (`queue-counts.ts`); none for a workflow with no item. */
|
|
167
164
|
readonly queue: Readonly<Record<Bucket, number>> | null;
|
|
168
165
|
/** What starts its runs. */
|
|
169
166
|
readonly startsOn: StartsOn;
|
|
@@ -173,11 +170,10 @@ export interface WorkflowView {
|
|
|
173
170
|
readonly place: PipelinePlace;
|
|
174
171
|
}
|
|
175
172
|
|
|
173
|
+
/** Every workflow, read at the request: nothing here is stored for the page. */
|
|
176
174
|
export interface WorkflowsView {
|
|
177
|
-
/** When it was
|
|
175
|
+
/** When it was read, unix seconds. */
|
|
178
176
|
readonly at: number;
|
|
179
|
-
readonly hours: number;
|
|
180
|
-
readonly since: number;
|
|
181
177
|
readonly groups: ReadonlyArray<{ readonly phase: string; readonly workflows: ReadonlyArray<WorkflowView> }>;
|
|
182
178
|
/** Where work goes between workflows: the DAG's edges (`workflow-flows.ts`). */
|
|
183
179
|
readonly flows: ReadonlyArray<WorkflowFlow>;
|
|
@@ -185,6 +181,24 @@ export interface WorkflowsView {
|
|
|
185
181
|
readonly queueHistory: ReadonlyArray<QueueCount>;
|
|
186
182
|
}
|
|
187
183
|
|
|
184
|
+
/** One workflow's figures over a window, read from its own records when it is opened. */
|
|
185
|
+
export interface WorkflowFigures {
|
|
186
|
+
readonly workflow: string;
|
|
187
|
+
/** When it was read, unix seconds, and the window: the `hours` before it. */
|
|
188
|
+
readonly at: number;
|
|
189
|
+
readonly hours: number;
|
|
190
|
+
readonly since: number;
|
|
191
|
+
readonly steps: ReadonlyArray<StepView>;
|
|
192
|
+
/** Its steps' costs added up. */
|
|
193
|
+
readonly total: StepCost;
|
|
194
|
+
readonly graph: WorkflowGraph;
|
|
195
|
+
readonly funnel: StepFunnel;
|
|
196
|
+
/** What a run of it costs, its processes included. */
|
|
197
|
+
readonly runCosts: RunCosts;
|
|
198
|
+
/** What its runs gave in the window, and in the window before it: the trend. */
|
|
199
|
+
readonly yields: { readonly now: Yield; readonly before: Yield };
|
|
200
|
+
}
|
|
201
|
+
|
|
188
202
|
const NO_COST: StepCost = { calls: 0, failed: 0, open: 0, seconds: 0, inputTokens: 0, outputTokens: 0, cpuSeconds: 0, compiles: 0, items: 0 };
|
|
189
203
|
|
|
190
204
|
const addCosts = (a: StepCost, b: StepCost): StepCost => ({
|
|
@@ -211,93 +225,110 @@ type Declared = Pick<WorkflowDeclaration<string, unknown>, 'name' | 'phase' | 'd
|
|
|
211
225
|
readonly steps: () => ReadonlyArray<StepDeclaration>;
|
|
212
226
|
};
|
|
213
227
|
|
|
214
|
-
|
|
228
|
+
const noTasks = (): Record<Bucket, number> => Object.fromEntries(BUCKETS.map((b) => [b, 0])) as Record<Bucket, number>;
|
|
229
|
+
|
|
230
|
+
/** Each queue's newest count from its history (`queueCountsSince`, oldest first), a bucket never counted at 0. Pure. */
|
|
231
|
+
export const queuesNow = (history: ReadonlyArray<QueueCount>): ReadonlyMap<string, Readonly<Record<Bucket, number>>> => {
|
|
232
|
+
const queues = new Map<string, Record<Bucket, number>>();
|
|
233
|
+
for (const row of history) {
|
|
234
|
+
const queue = queues.get(row.workflow) ?? noTasks();
|
|
235
|
+
if ((BUCKETS as ReadonlyArray<string>).includes(row.bucket)) queue[row.bucket as Bucket] = row.tasks;
|
|
236
|
+
queues.set(row.workflow, queue);
|
|
237
|
+
}
|
|
238
|
+
return queues;
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* EVERY WORKFLOW AS A PAGE SHOWS IT BEFORE ONE IS OPENED, READ AT THE REQUEST: the declarations, the limits, each queue's
|
|
243
|
+
* counts as last counted and their history, and where work goes between workflows. Four small readings of the store, so a
|
|
244
|
+
* page load needs no stored copy of it. `limitsOf` is none where no store is read.
|
|
245
|
+
*/
|
|
215
246
|
export const buildWorkflowsView = (input: {
|
|
216
247
|
readonly declared: ReadonlyArray<Declared>;
|
|
217
248
|
/** The project's phases, in the order its page shows them; a workflow of another phase follows them. */
|
|
218
249
|
readonly phases: ReadonlyArray<string>;
|
|
219
250
|
readonly now: number;
|
|
220
|
-
readonly hours: number;
|
|
221
|
-
readonly records: StepRecords;
|
|
222
|
-
readonly engine: EngineRecords;
|
|
223
|
-
readonly tasks: Pick<Tasks, 'taskSummaries'>;
|
|
224
251
|
/** The queues' history and the new input between workflows, from the task store. */
|
|
225
252
|
readonly taskStore: Pick<TaskStore, 'queueCountsSince' | 'newInputFlows' | 'listedWaits'>;
|
|
226
253
|
/** The line a definition's text is on now. */
|
|
227
254
|
readonly locate: (source: SourceRef) => number | null;
|
|
228
255
|
readonly limitsOf: (workflow: string) => WorkflowView['limits'];
|
|
229
|
-
readonly pausedOf: (workflow: string) => string | null;
|
|
230
256
|
}): Effect.Effect<WorkflowsView, StorageError> => Effect.gen(function* () {
|
|
231
|
-
const since = input.now - input.hours * 3600;
|
|
232
|
-
const before = since - input.hours * 3600;
|
|
233
|
-
const rows = yield* input.records.stepRunsSince(since);
|
|
234
|
-
// The window before, for the trend: its records are those since its start, less the window's own.
|
|
235
|
-
const rowsBoth = yield* input.records.stepRunsSince(before);
|
|
236
|
-
const funnelRecords = yield* input.records.funnelRecordsSince(since);
|
|
237
|
-
const funnelBoth = yield* input.records.funnelRecordsSince(before);
|
|
238
|
-
const finishedNow = yield* input.records.runOutcomesSince(since);
|
|
239
|
-
const runCosts = yield* input.records.runCostsSince(since);
|
|
240
|
-
const finishedBoth = yield* input.records.runOutcomesSince(before);
|
|
241
|
-
const moves = yield* input.records.stepEdgesSince(since);
|
|
242
|
-
const going = new Set((yield* input.engine.unfinishedRuns()).map((u) => u.run));
|
|
243
|
-
const queues = new Map(yield* Effect.forEach(input.declared.filter((d) => d.item !== null), (d) =>
|
|
244
|
-
Effect.map(input.tasks.taskSummaries({ workflow: d.name }), (tasks) => [d.name, bucketCounts(tasks)] as const)));
|
|
245
|
-
const graphs = new Map(workflowGraphs({ declared: input.declared, taken: moves.edges, lasts: moves.lasts, going }).map((g) => [g.workflow, g]));
|
|
246
257
|
const flows = workflowFlows({ declared: input.declared, newInputs: yield* input.taskStore.newInputFlows(), waits: yield* input.taskStore.listedWaits() });
|
|
247
258
|
const phases = [...input.phases, ...[...new Set(input.declared.map((d) => d.phase))].filter((p) => !input.phases.includes(p))];
|
|
248
259
|
const places = new Map(pipelinePlaces({ workflows: input.declared.map((d) => ({ name: d.name, stage: d.phase })), stages: phases, flows }).map((p) => [p.workflow, p]));
|
|
249
260
|
const queueHistory = yield* input.taskStore.queueCountsSince(input.now - QUEUE_HISTORY_DAYS * 86_400);
|
|
250
|
-
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
...onlyInRecords.map((name) => ({ name, agent: own.some((r) => r.step === name && r.agent === 1), description: 'no longer declared', source: link(d.source), declared: false, cost: costOf(own.filter((r) => r.step === name)), endings: endingsOf(ownRecords.filter((r) => r.step === name)) })),
|
|
261
|
-
];
|
|
262
|
-
const funnel = stepFunnel({
|
|
263
|
-
declaration: d, records: ownRecords, outcomes: funnelRecords.outcomes.filter((o) => o.workflow === d.name),
|
|
264
|
-
unfinished: going, hours: input.hours, since, now: input.now,
|
|
265
|
-
});
|
|
266
|
-
const funnelBefore = stepFunnel({
|
|
267
|
-
declaration: d, records: funnelBoth.records.filter((r) => r.workflow === d.name), outcomes: funnelBoth.outcomes.filter((o) => o.workflow === d.name),
|
|
268
|
-
unfinished: going, hours: input.hours, since: before, now: since,
|
|
269
|
-
});
|
|
270
|
-
const costNow = costOf(own) ?? NO_COST;
|
|
271
|
-
const costBoth = costOf(rowsBoth.filter((r) => r.workflow === d.name)) ?? NO_COST;
|
|
272
|
-
const finished = (outcomes: ReadonlyArray<RunOutcomeRow>) => outcomes.filter((o) => o.workflow === d.name && o.finished === 1).length;
|
|
273
|
-
return {
|
|
274
|
-
steps,
|
|
275
|
-
funnel,
|
|
276
|
-
runCosts: runCostsOf(runCosts.filter((c) => c.workflow === d.name)),
|
|
277
|
-
yields: {
|
|
278
|
-
now: yieldOf({ runs: funnel.runs, finished: finished(finishedNow), tokens: costNow.inputTokens + costNow.outputTokens, compiles: costNow.compiles }),
|
|
279
|
-
before: yieldOf({
|
|
280
|
-
runs: funnelBefore.runs, finished: finished(finishedBoth) - finished(finishedNow),
|
|
281
|
-
tokens: costBoth.inputTokens + costBoth.outputTokens - (costNow.inputTokens + costNow.outputTokens), compiles: costBoth.compiles - costNow.compiles,
|
|
282
|
-
}),
|
|
283
|
-
},
|
|
284
|
-
name: d.name, phase: d.phase, description: d.description, source: link(d.source), item: d.item, finishedWord: d.finishedWord,
|
|
285
|
-
usesAgents: declaredSteps.some((s) => s.agent),
|
|
286
|
-
limits: input.limitsOf(d.name),
|
|
287
|
-
paused: input.pausedOf(d.name),
|
|
288
|
-
total: steps.reduce((t, s) => (s.cost === null ? t : addCosts(t, s.cost)), NO_COST),
|
|
289
|
-
graph: graphs.get(d.name)!,
|
|
290
|
-
queue: queues.get(d.name) ?? null,
|
|
291
|
-
startsOn: d.pending !== undefined ? { kind: 'queue' } : d.inputs !== undefined ? { kind: 'inputs', says: d.inputs.says } : { kind: 'timer or request' },
|
|
292
|
-
fedBy: d.fedBy ?? [],
|
|
293
|
-
place: places.get(d.name)!,
|
|
294
|
-
};
|
|
295
|
-
};
|
|
296
|
-
|
|
261
|
+
const queues = queuesNow(queueHistory);
|
|
262
|
+
const workflowView = (d: Declared): WorkflowView => ({
|
|
263
|
+
name: d.name, phase: d.phase, description: d.description, source: { ...d.source, line: input.locate(d.source) }, item: d.item, finishedWord: d.finishedWord,
|
|
264
|
+
usesAgents: d.steps().some((s) => s.agent),
|
|
265
|
+
limits: input.limitsOf(d.name),
|
|
266
|
+
queue: d.item === null ? null : queues.get(d.name) ?? noTasks(),
|
|
267
|
+
startsOn: d.pending !== undefined ? { kind: 'queue' } : d.inputs !== undefined ? { kind: 'inputs', says: d.inputs.says } : { kind: 'timer or request' },
|
|
268
|
+
fedBy: d.fedBy ?? [],
|
|
269
|
+
place: places.get(d.name)!,
|
|
270
|
+
});
|
|
297
271
|
return {
|
|
298
|
-
at: input.now,
|
|
272
|
+
at: input.now,
|
|
299
273
|
groups: phases.map((phase) => ({ phase, workflows: input.declared.filter((d) => d.phase === phase).map(workflowView) })).filter((g) => g.workflows.length > 0),
|
|
300
274
|
flows,
|
|
301
275
|
queueHistory,
|
|
302
276
|
};
|
|
303
277
|
});
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* ONE WORKFLOW'S FIGURES OVER THE `hours` BEFORE `now`, READ FROM ITS OWN RECORDS when a page opens it: each step's cost and
|
|
281
|
+
* endings, its step graph with the runs on each edge, where its runs stopped, what a run costs, and what its runs gave
|
|
282
|
+
* against the window before.
|
|
283
|
+
*/
|
|
284
|
+
export const buildWorkflowFigures = (input: {
|
|
285
|
+
readonly declaration: Declared;
|
|
286
|
+
readonly now: number;
|
|
287
|
+
readonly hours: number;
|
|
288
|
+
readonly records: StepRecords;
|
|
289
|
+
readonly engine: EngineRecords;
|
|
290
|
+
/** The line a definition's text is on now. */
|
|
291
|
+
readonly locate: (source: SourceRef) => number | null;
|
|
292
|
+
}): Effect.Effect<WorkflowFigures, StorageError> => Effect.gen(function* () {
|
|
293
|
+
const d = input.declaration;
|
|
294
|
+
const since = input.now - input.hours * 3600;
|
|
295
|
+
const before = since - input.hours * 3600;
|
|
296
|
+
const own = yield* input.records.stepRunsSince(since, d.name);
|
|
297
|
+
// The window before, for the trend: its records are those since its start, less the window's own.
|
|
298
|
+
const ownBoth = yield* input.records.stepRunsSince(before, d.name);
|
|
299
|
+
const funnelRecords = yield* input.records.funnelRecordsSince(since, d.name);
|
|
300
|
+
const funnelBoth = yield* input.records.funnelRecordsSince(before, d.name);
|
|
301
|
+
const finishedNow = yield* input.records.runOutcomesSince(since, d.name);
|
|
302
|
+
const finishedBoth = yield* input.records.runOutcomesSince(before, d.name);
|
|
303
|
+
const runCosts = yield* input.records.runCostsSince(since, d.name);
|
|
304
|
+
const moves = yield* input.records.stepEdgesSince(since, d.name);
|
|
305
|
+
const going = new Set((yield* input.engine.unfinishedRuns()).map((u) => u.run));
|
|
306
|
+
const link = (s: SourceRef): SourceLink => ({ ...s, line: input.locate(s) });
|
|
307
|
+
|
|
308
|
+
const declaredSteps = d.steps();
|
|
309
|
+
const onlyInRecords = [...new Set(own.map((r) => r.step))].filter((s) => !declaredSteps.some((x) => x.name === s));
|
|
310
|
+
const steps: ReadonlyArray<StepView> = [
|
|
311
|
+
...declaredSteps.map((s) => ({ name: s.name, agent: s.agent, description: s.description, source: link(s.source), declared: true, cost: costOf(own.filter((r) => r.step === s.name)), endings: endingsOf(funnelRecords.records.filter((r) => r.step === s.name)) })),
|
|
312
|
+
...onlyInRecords.map((name) => ({ name, agent: own.some((r) => r.step === name && r.agent === 1), description: 'no longer declared', source: link(d.source), declared: false, cost: costOf(own.filter((r) => r.step === name)), endings: endingsOf(funnelRecords.records.filter((r) => r.step === name)) })),
|
|
313
|
+
];
|
|
314
|
+
const funnel = stepFunnel({ declaration: d, records: funnelRecords.records, outcomes: funnelRecords.outcomes, unfinished: going, hours: input.hours, since, now: input.now });
|
|
315
|
+
const funnelBefore = stepFunnel({ declaration: d, records: funnelBoth.records, outcomes: funnelBoth.outcomes, unfinished: going, hours: input.hours, since: before, now: since });
|
|
316
|
+
const costNow = costOf(own) ?? NO_COST;
|
|
317
|
+
const costBoth = costOf(ownBoth) ?? NO_COST;
|
|
318
|
+
const finished = (outcomes: ReadonlyArray<RunOutcomeRow>) => outcomes.filter((o) => o.finished === 1).length;
|
|
319
|
+
return {
|
|
320
|
+
workflow: d.name, at: input.now, hours: input.hours, since,
|
|
321
|
+
steps,
|
|
322
|
+
total: steps.reduce((t, s) => (s.cost === null ? t : addCosts(t, s.cost)), NO_COST),
|
|
323
|
+
graph: workflowGraphs({ declared: [d], taken: moves.edges, lasts: moves.lasts, going })[0]!,
|
|
324
|
+
funnel,
|
|
325
|
+
runCosts: runCostsOf(runCosts),
|
|
326
|
+
yields: {
|
|
327
|
+
now: yieldOf({ runs: funnel.runs, finished: finished(finishedNow), tokens: costNow.inputTokens + costNow.outputTokens, compiles: costNow.compiles }),
|
|
328
|
+
before: yieldOf({
|
|
329
|
+
runs: funnelBefore.runs, finished: finished(finishedBoth) - finished(finishedNow),
|
|
330
|
+
tokens: costBoth.inputTokens + costBoth.outputTokens - (costNow.inputTokens + costNow.outputTokens), compiles: costBoth.compiles - costNow.compiles,
|
|
331
|
+
}),
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
});
|