From df292705146fb6ad09ee5c1ea25d9b67631ea840 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:59:51 +0000 Subject: [PATCH 1/2] feat(automation): record a run's wait time beside its duration Adds an optional waitMs to the published run record (ExecutionLog) and fills it on every run-record writer: 0 for a run that never paused, the sum of every pause for a resumed run. The engine keeps one wait clock per suspension (activeMs, persisted as sys_automation_run.active_ms) and the terminal row carries wait_ms. Claude-Session: https://claude.ai/code/session_016WV4cxHwXNcGcAHNerZsom Co-authored-by: Claude --- .../src/consumed-suspension-restore.ts | 14 +++- .../service-automation/src/dag-traversal.ts | 12 +++- .../services/service-automation/src/engine.ts | 67 ++++++++++++++++++- .../service-automation/src/run-history.ts | 9 +++ .../service-automation/src/run-resume.ts | 36 ++++++++-- .../src/suspended-run-store.ts | 26 +++++++ .../src/sys-automation-run.object.ts | 23 +++++++ .../spec/src/automation/execution.test.ts | 28 ++++++++ packages/spec/src/automation/execution.zod.ts | 22 ++++++ 9 files changed, 228 insertions(+), 9 deletions(-) diff --git a/packages/services/service-automation/src/consumed-suspension-restore.ts b/packages/services/service-automation/src/consumed-suspension-restore.ts index f7cfe9f779b..ea71d69215a 100644 --- a/packages/services/service-automation/src/consumed-suspension-restore.ts +++ b/packages/services/service-automation/src/consumed-suspension-restore.ts @@ -17,7 +17,7 @@ import { describeThrownForLog } from './thrown-cause-diagnostics.js'; // The values below (`MAX_CONSUMED_SUSPENSIONS`, `MAX_RESTORE_CHAIN_HOPS`, -// `buildRunTrigger`, `chainEntryOf` and `nestedChildRunId`) are read only +// `buildRunTrigger`, `chainEntryOf`, `nestedChildRunId` and `waitOfPausedRun`) are read only // inside the function bodies, at call time, never while a module is // evaluating, so the import cycle with ./engine.js is safe under ESM live // bindings; the tsup bundle is one file and has no cycle. @@ -27,6 +27,7 @@ import { buildRunTrigger, chainEntryOf, nestedChildRunId, + waitOfPausedRun, type AutomationEngine, type ChainRestoreEntry, type ConsumedSuspension, @@ -457,13 +458,22 @@ export async function restoreOneConsumedSuspension( // row: `ExecutionStatus` carries no such member, so a durable // status that survives the restart is a spec-vocabulary decision // nobody has taken — the row's discriminator stays the snapshot. + // + // [#32284] `waitMs` from the SNAPSHOT's clock: the restore re-arms the + // pause the failed resume consumed, so the run reads as never having + // left it — the attempt that failed, the time it sat stranded and the + // wait from here to its next resume are all one pause, and its active + // time is still what it had executed when it first parked. That is + // also what its step log says: the snapshot's steps end at the pause. + const durationMs = Date.now() - consumed.run.startTime; this.recordLog({ id: runId, flowName: consumed.run.flowName, flowVersion: consumed.run.flowVersion, status: 'paused', startedAt: consumed.run.startedAt, - durationMs: Date.now() - consumed.run.startTime, + durationMs, + waitMs: waitOfPausedRun(consumed.run, durationMs), trigger: buildRunTrigger(consumed.run.context), steps: consumed.run.steps, variables: consumed.run.variables, diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index 93aab66eda9..c32db9e0ea8 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -24,10 +24,11 @@ import { summarizeRun } from './run-summary.js'; import { withDroppedFields } from './run-dropped-fields.js'; import { describeThrownForLog } from './thrown-cause-diagnostics.js'; // The values below (`AutomationEngine` for its public static -// `MAX_NODE_REENTRIES`) are read only inside the function bodies, at call time, +// `MAX_NODE_REENTRIES`, and `activeMsAtPause`) are read only inside the function bodies, at call time, // never while a module is evaluating, so the import cycle with ./engine.js is // safe under ESM live bindings; the tsup bundle is one file and has no cycle. import { + activeMsAtPause, AutomationEngine, buildRunTrigger, DEFAULT_BRANCH_LABEL, @@ -1361,6 +1362,8 @@ export async function executeWithoutRetry( startedAt, completedAt: new Date().toISOString(), durationMs, + // [#32284] A retry attempt is an initial execution: it never paused. + waitMs: 0, trigger: buildRunTrigger(context), steps, output, @@ -1421,7 +1424,7 @@ export async function executeWithoutRetry( if (isRefusalSignal(err)) { return this.finishRefusedRun({ runId, flowName, flowVersion: flow.version, - startedAt, durationMs: Date.now() - startTime, + startedAt, durationMs: Date.now() - startTime, waitMs: 0, steps, flow, variables, refusalMessage: err.message, context, }); @@ -1468,6 +1471,8 @@ export async function executeWithoutRetry( // method returns — the only id `resume()` can be called with. if (isSuspendSignal(err)) { const durationMs = Date.now() - startTime; + // [#32284] This attempt's first pause — see `execute()`'s. + const waitMs = 0; // #7639 — ONE snapshot expression feeding BOTH consumers: the // continuation the run will resume from, and the `paused` log // entry run-detail serves. Same object, so what an operator @@ -1485,6 +1490,7 @@ export async function executeWithoutRetry( context: runContext, startedAt, startTime, + activeMs: activeMsAtPause(durationMs, waitMs), correlation: err.correlation, screen: err.screen, }); @@ -1495,6 +1501,7 @@ export async function executeWithoutRetry( status: 'paused', startedAt, durationMs, + waitMs, trigger: buildRunTrigger(context), steps, variables: variablesSnapshot, @@ -1539,6 +1546,7 @@ export async function executeWithoutRetry( startedAt, completedAt: new Date().toISOString(), durationMs, + waitMs: 0, trigger: buildRunTrigger(context), steps, error: errorMessage, diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 43c586524a6..3c90925667a 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -1294,6 +1294,13 @@ export interface ExecutionLogEntry { startedAt: string; completedAt?: string; durationMs?: number; + /** + * [#32284] `ExecutionLogSchema.waitMs`: the part of `durationMs` the run + * spent suspended, summed over every pause it has left — `0` on a run + * that never paused, absent when not recorded. Written beside `durationMs` + * at every site that writes one; never derived from it here. + */ + waitMs?: number; trigger: { type: string; userId?: string; object?: string; recordId?: string }; // ↑ built by `buildRunTrigger` at EVERY site — see its doc comment for why // that is a chokepoint rather than eight object literals. @@ -1776,11 +1783,52 @@ export interface SuspendedRun { context: AutomationContext; startedAt: string; startTime: number; + /** + * [#32284] The run's wait clock: the milliseconds it had spent EXECUTING + * (its age at this pause minus every earlier pause) when it paused here. + * Nothing executes while the run is parked, so at any later instant the + * run's total wait is its age minus this — which is how one number sums + * every pause of a run that suspends, resumes and suspends again + * ({@link waitOfPausedRun}), and why a restore that re-arms a consumed + * pause needs no clock of its own: the snapshot carries this value, and + * the time from the pause to the restore is wait like the rest of it. + * + * Set at every site that builds a suspension ({@link activeMsAtPause}); + * carried unchanged by every re-save of the SAME pause (`{ ...run }`). + * Absent on a suspension recorded before this field existed, or by a + * host store that does not round-trip it: such a run's `waitMs` is not + * recorded rather than guessed. + */ + activeMs?: number; correlation?: string; /** Screen the run paused on (screen-flow runtime), for re-fetch + UI render. */ screen?: ScreenSpec; } +/** + * [#32284] The `activeMs` a suspension records: the run's age at the pause + * minus the wait it has already accumulated. `undefined` when that wait is not + * known (the run's previous pause carried no clock), so an unknown wait is + * never turned into a precise-looking number further on. + */ +export function activeMsAtPause(elapsedMs: number, waitMs: number | undefined): number | undefined { + return waitMs === undefined ? undefined : Math.max(0, elapsedMs - waitMs); +} + +/** + * [#32284] A paused run's total wait at the moment its pause ENDS — a resume + * consumes it, or the run is cancelled, failed or settled where it waits, or a + * restore records it paused again: its age then (`elapsedMs`, measured from + * `startTime` like `durationMs`) minus the time it had spent executing when it + * paused. `undefined` for a suspension with no clock ({@link SuspendedRun.activeMs}). + * + * Clamped at zero: `startTime` may have been stamped by another replica's + * clock, and a published `waitMs` is never negative. + */ +export function waitOfPausedRun(run: Pick, elapsedMs: number): number | undefined { + return typeof run.activeMs === 'number' ? Math.max(0, elapsedMs - run.activeMs) : undefined; +} + /** * Pluggable durable store for suspended runs (ADR-0019). The engine persists a * {@link SuspendedRun} on suspend and deletes it on terminal completion; on @@ -1868,6 +1916,13 @@ export interface RunRecord { /** When the run reached its terminal state. */ finishedAt?: string; durationMs?: number; + /** + * [#32284] The run's {@link ExecutionLogEntry.waitMs}, persisted beside + * `durationMs` (`sys_automation_run.wait_ms`) so a run read back after a + * restart or a ring eviction still says how much of its duration was + * waiting. Absent on a row written before the column existed. + */ + waitMs?: number; /** Failure reason for a `failed` run — what a designer needs to fix it. */ error?: string; /** @@ -7726,6 +7781,8 @@ export class AutomationEngine implements IAutomationService { startedAt, completedAt: new Date().toISOString(), durationMs, + // [#32284] The initial execution never paused: a measured 0. + waitMs: 0, trigger: buildRunTrigger(context), steps, output, @@ -7824,7 +7881,7 @@ export class AutomationEngine implements IAutomationService { if (isRefusalSignal(err)) { return this.finishRefusedRun({ runId, flowName, flowVersion: flow.version, - startedAt, durationMs: Date.now() - startTime, + startedAt, durationMs: Date.now() - startTime, waitMs: 0, steps, flow, variables, refusalMessage: err.message, context, }); @@ -7834,6 +7891,9 @@ export class AutomationEngine implements IAutomationService { // caller can later `resume()` it. This is NOT a failure. if (isSuspendSignal(err)) { const durationMs = Date.now() - startTime; + // [#32284] The run's first pause: nothing waited yet, so all + // of `durationMs` was execution — the clock the resume reads. + const waitMs = 0; // #7639 — ONE snapshot expression feeding BOTH consumers: the // continuation the run will resume from, and the `paused` log // entry run-detail serves. Same object, so what an operator @@ -7852,6 +7912,7 @@ export class AutomationEngine implements IAutomationService { context: runContext, startedAt, startTime, + activeMs: activeMsAtPause(durationMs, waitMs), correlation: err.correlation, screen: err.screen, }); @@ -7862,6 +7923,7 @@ export class AutomationEngine implements IAutomationService { status: 'paused', startedAt, durationMs, + waitMs, trigger: buildRunTrigger(context), steps, variables: variablesSnapshot, @@ -7926,6 +7988,7 @@ export class AutomationEngine implements IAutomationService { startedAt, completedAt: new Date().toISOString(), durationMs, + waitMs: 0, trigger: buildRunTrigger(context), steps, error: errorMessage, @@ -9943,6 +10006,8 @@ export class AutomationEngine implements IAutomationService { flowVersion?: number; startedAt: string; durationMs: number; + /** [#32284] The run's `waitMs` — `undefined` only where it is not recorded. */ + waitMs: number | undefined; steps: StepLogEntry[]; /** Read for its `isOutput` variable declarations — see `output` below. */ flow: FlowParsed; diff --git a/packages/services/service-automation/src/run-history.ts b/packages/services/service-automation/src/run-history.ts index 8d6c532fe84..b60e2baaf0e 100644 --- a/packages/services/service-automation/src/run-history.ts +++ b/packages/services/service-automation/src/run-history.ts @@ -270,6 +270,9 @@ export function runRecordToLogEntry(r: RunRecord): ExecutionLogEntry { startedAt: r.startedAt, completedAt: r.finishedAt, durationMs: r.durationMs, + // [#32284] The persisted wait — absent on a row written before the + // column existed, which reads "not recorded", never "did not wait". + waitMs: r.waitMs, // #7533 — the persisted trigger attribution, so a run rehydrated // after a restart still says what fired it and (for a record // change) which record. `type` falls back to `''` ONLY for rows @@ -615,6 +618,9 @@ export function recordLog( startedAt: entry.startedAt, finishedAt: entry.completedAt, durationMs: entry.durationMs, + // [#32284] Beside `durationMs`, so the durable row answers "how + // much of that was waiting?" after a restart as the ring does. + waitMs: entry.waitMs, error: entry.error, // [#15788] The rendered refusal, carried onto the durable row // beside `status: 'refused'`. Set by exactly one producer @@ -717,6 +723,8 @@ export function finishRefusedRun(this: Pick(row.context_json, {}), startedAt, startTime: typeof row.start_time === 'number' ? row.start_time : (Date.parse(startedAt) || Date.now()), + ...readActiveMs(row), correlation: row.correlation ?? undefined, screen: parseJson(row.screen_json, undefined as any), }; @@ -1049,6 +1058,8 @@ function serializeConsumedSuspension( correlation: null, // [#28405] The identity a restore re-arms the pause pinned to. flow_checksum: null, + // [#32284] The wait clock a restore re-arms the pause with. + active_ms: null, }; if (!run) return empty; const variables_json = JSON.stringify(run.variables ?? {}); @@ -1092,6 +1103,11 @@ function serializeConsumedSuspension( node_type: run.nodeType ?? null, correlation: run.correlation ?? null, flow_checksum: run.flowChecksum ?? null, + // [#32284] The consumed pause's wait clock, in the column the paused row + // keeps it in — so a restore from this row re-arms the pause with it and + // the run's eventual `waitMs` still sums every pause. `wait_ms` on this + // row is the FAILED record's own wait; the two never share a column. + active_ms: run.activeMs ?? null, }; } @@ -1113,6 +1129,15 @@ function readFlowChecksum(row: any): string | undefined { return typeof row.flow_checksum === 'string' && row.flow_checksum !== '' ? row.flow_checksum : undefined; } +/** + * [#32284] A paused row's (or a consumed snapshot's) wait clock, as + * `SuspendedRun.activeMs` — nothing for a row written before the column + * existed, whose run then records no `waitMs` rather than a guessed one. + */ +function readActiveMs(row: any): { activeMs?: number } { + return typeof row.active_ms === 'number' ? { activeMs: row.active_ms } : {}; +} + /** * [#13909] Rebuild a terminal row's consumed-suspension snapshot, or * `undefined` when the row carries none. @@ -1157,6 +1182,7 @@ function deserializeConsumedSuspension(row: any): SuspendedRun | undefined { context: parseJson(row.context_json, {}), startedAt, startTime: typeof row.start_time === 'number' ? row.start_time : (Date.parse(startedAt) || Date.now()), + ...readActiveMs(row), correlation: row.correlation ?? undefined, screen: parseJson(row.screen_json, undefined as any), }; diff --git a/packages/services/service-automation/src/sys-automation-run.object.ts b/packages/services/service-automation/src/sys-automation-run.object.ts index 1fd8e9c49d7..dc8052e276d 100644 --- a/packages/services/service-automation/src/sys-automation-run.object.ts +++ b/packages/services/service-automation/src/sys-automation-run.object.ts @@ -399,6 +399,20 @@ export const SysAutomationRun = ObjectSchema.create({ group: 'State', }), + // [#32284] The wait clock of a paused run, and the reason it is ONE + // number: nothing executes while a run is parked, so at any later instant + // the run's total wait is its age minus the time it had spent executing + // when it paused. A resume reads it to fill `wait_ms`; a run that pauses + // again writes it forward, which is how every pause of a multi-stage run is + // summed. On a stranded terminal row it is the consumed pause's clock, with + // the rest of that snapshot (`variables_json`, `node_type`, …). + active_ms: Field.number({ + label: 'Active Time Before Pause (ms)', + required: false, + description: 'On a paused run: the milliseconds it had spent executing when it paused (its age minus every earlier pause) — the clock its resume derives `wait_ms` from. On a failed run whose resume consumed a pause: that pause\'s value, for a restore. Null otherwise, and on rows written before this was tracked.', + group: 'State', + }), + finished_at: Field.datetime({ label: 'Finished At', required: false, @@ -413,6 +427,15 @@ export const SysAutomationRun = ObjectSchema.create({ group: 'Outcome', }), + // [#32284] `ExecutionLog.waitMs` on the durable row, so a run read back + // after a restart or a ring eviction still separates waiting from work. + wait_ms: Field.number({ + label: 'Wait (ms)', + required: false, + description: 'The part of `duration_ms` the run spent suspended (at a screen, approval, wait or other pausing node), summed over all its pauses — so `duration_ms - wait_ms` is the time it spent executing. 0 for a run that never paused; null on rows written before this was tracked, which is not the same as zero.', + group: 'Outcome', + }), + error: Field.textarea({ label: 'Error', required: false, diff --git a/packages/spec/src/automation/execution.test.ts b/packages/spec/src/automation/execution.test.ts index 1184a00b9cc..58d397b1d45 100644 --- a/packages/spec/src/automation/execution.test.ts +++ b/packages/spec/src/automation/execution.test.ts @@ -395,6 +395,34 @@ describe('ExecutionLogSchema', () => { startedAt: '2026-02-01T10:00:00Z', })).toThrow(); // missing trigger }); + + describe('a run\'s waitMs (#32284)', () => { + const resumedScreenRun = { + id: 'run_screen', flowName: 'collect_details', status: 'completed' as const, + trigger: { type: 'manual' }, steps: [validStep], + startedAt: '2026-02-01T10:00:00Z', completedAt: '2026-02-01T10:00:18.691Z', + durationMs: 18691, waitMs: 18500, + }; + + it('keeps it through a parse beside durationMs, so a client validating the run reads both', () => { + const log = ExecutionLogSchema.parse(resumedScreenRun); + expect(log.waitMs).toBe(18500); + expect(log.durationMs).toBe(18691); + }); + + it('stays absent on a run that carries none, never defaulted to 0', () => { + const { waitMs: _omitted, ...unrecorded } = resumedScreenRun; + expect('waitMs' in ExecutionLogSchema.parse(unrecorded)).toBe(false); + }); + + it('refuses a negative or fractional value at its path', () => { + for (const waitMs of [-1, 1.5]) { + const res = ExecutionLogSchema.safeParse({ ...resumedScreenRun, waitMs }); + expect(res.success).toBe(false); + expect(res.error?.issues[0].path).toEqual(['waitMs']); + } + }); + }); }); // ========================================== diff --git a/packages/spec/src/automation/execution.zod.ts b/packages/spec/src/automation/execution.zod.ts index 58a3f3c87f5..2184cfca6af 100644 --- a/packages/spec/src/automation/execution.zod.ts +++ b/packages/spec/src/automation/execution.zod.ts @@ -433,6 +433,28 @@ export const ExecutionLogSchema = lazySchema(() => z.object({ startedAt: z.string().datetime().describe('Execution start timestamp'), completedAt: z.string().datetime().optional().describe('Execution completion timestamp'), durationMs: z.number().int().min(0).optional().describe('Total execution duration in milliseconds'), + /** + * #32284 (ruled option A): the part of `durationMs` the run spent + * SUSPENDED — parked at a `screen`, `approval`, `wait` or other pausing + * node for a person, a timer or an event — summed over all its pauses. + * `durationMs` keeps its meaning (total wall time, pauses + * included), so the time the run spent executing is derived, never stored: + * `durationMs - waitMs`. A resumed screen flow that reported 18.7 s was + * almost all its user's wait, and nothing on the record said so. + * + * Same convention as `FlowRunSummary.failed`: `0` is a measured fact (the + * run never paused, or is paused for the first time), and absent means not + * recorded — a `missed` entry, where nothing ran and `durationMs` is absent + * too, or a run whose pause predates this field. Absent is not zero. A + * `paused` entry measures both members at the moment it was written, so + * `durationMs - waitMs` holds there too. + */ + waitMs: z.number().int().min(0).optional().describe( + 'Total time the run spent suspended (waiting at a `screen`, `approval`, `wait` or other pausing node), summed over all its pauses, in milliseconds. ' + + 'Included in `durationMs`, which stays the total wall time, so the time spent executing is `durationMs - waitMs`. ' + + '`0` on a run that never paused; on a `paused` entry, the wait up to the moment the entry was written. ' + + 'Absent when not recorded — a `missed` entry, or a run paused before this was tracked — which is not the same as zero.', + ), /** Context */ runAs: z.enum(['system', 'user']).optional().describe('Execution context identity'), From 50c4166cabb364947c6aab50739e07eb4eeefb17 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:18:45 +0000 Subject: [PATCH 2/2] test(automation): pin a run's wait time across pauses, restarts and the restore Pins the summed wait on every run-record path: a run that never paused, one pause, two pauses across fresh engines over one store, a cancel where the run waits, a stranded resume restored by an operator, and a suspension parked without a clock. A second group drives the object store over one table and reads the active_ms and wait_ms cells, so a mapper that never wrote a column cannot pass. Regenerates the authorable-surface baseline and the reference docs, and adds the changeset. Claude-Session: https://claude.ai/code/session_016WV4cxHwXNcGcAHNerZsom Co-authored-by: Claude --- .changeset/32284-run-wait-ms.md | 17 ++ .../docs/references/api/automation-api.mdx | 1 + .../docs/references/automation/execution.mdx | 1 + .../src/run-wait-time.test.ts | 269 ++++++++++++++++++ .../src/suspended-run-store.test.ts | 133 ++++++++- .../spec/authorable-surface/automation.json | 1 + 6 files changed, 421 insertions(+), 1 deletion(-) create mode 100644 .changeset/32284-run-wait-ms.md create mode 100644 packages/services/service-automation/src/run-wait-time.test.ts diff --git a/.changeset/32284-run-wait-ms.md b/.changeset/32284-run-wait-ms.md new file mode 100644 index 00000000000..659b511bae4 --- /dev/null +++ b/.changeset/32284-run-wait-ms.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-automation': minor +--- + +feat(automation): a run record says how much of its duration the run spent suspended, so a resumed screen flow no longer reads as an 18-second execution + +Clause-②: yes (widening) +Metadata-protocol: added + +A run's `durationMs` is its total wall time, pauses included. A screen flow resumed after the user filled the screen in reported `durationMs: 18691`, almost all of it the user's wait, and nothing on the record told an admin that the run was waiting rather than slow. + +`ExecutionLogSchema` (`@objectstack/spec/automation`), the run record served by `GET /api/v1/automation/:name/runs/:runId` and the runs list, gains an optional `waitMs`: the total time the run spent suspended at a `screen`, `approval`, `wait` or other pausing node, summed over all its pauses. `durationMs` keeps its meaning, so the time a run spent executing is `durationMs - waitMs`. A run that never paused carries `waitMs: 0`, a measured zero; a `paused` entry carries the wait up to the moment it was written. Absent means not recorded (a `missed` entry, or a run paused before this release), which is not the same as zero. + +`@objectstack/service-automation` fills it on every run record: initial execution and its retries, resume (completed, refused, stranded, re-suspended), a paused run cancelled or failed where it waits, and the operator restore of a consumed suspension, which keeps the clock of the pause it re-arms. A suspension carries one number, `SuspendedRun.activeMs` (the time the run had executed when it paused), so the wait sums across any number of pauses and process restarts. `sys_automation_run` gains two nullable columns: `active_ms` on paused rows (and on a stranded row's consumed snapshot) and `wait_ms` on terminal rows. + +Nothing to migrate: rows written before this release keep both columns empty and read `waitMs` as not recorded. A client that validates the run record with `ExecutionLogSchema` from an older `@objectstack/spec` strips the new member and reads the record as before. diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index 732dfca51c7..f8f2cca1038 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -937,6 +937,7 @@ const result = AutomationApiErrorCode.parse(data); | **startedAt** | `string` | ✅ | Execution start timestamp | | **completedAt** | `string` | optional | Execution completion timestamp | | **durationMs** | `integer` | optional | Total execution duration in milliseconds | +| **waitMs** | `integer` | optional | Total time the run spent suspended (waiting at a `screen`, `approval`, `wait` or other pausing node), summed over all its pauses, in milliseconds. Included in `durationMs`, which stays the total wall time, so the time spent executing is `durationMs - waitMs`. `0` on a run that never paused; on a `paused` entry, the wait up to the moment the entry was written. Absent when not recorded — a `missed` entry, or a run paused before this was tracked — which is not the same as zero. | | **runAs** | `Enum<'system' \| 'user'>` | optional | Execution context identity | | **tenantId** | `string` | optional | Tenant ID for multi-tenant isolation | diff --git a/content/docs/references/automation/execution.mdx b/content/docs/references/automation/execution.mdx index db2021f23d5..610c160b022 100644 --- a/content/docs/references/automation/execution.mdx +++ b/content/docs/references/automation/execution.mdx @@ -113,6 +113,7 @@ const result = CheckpointSchema.parse(data); | **startedAt** | `string` | ✅ | Execution start timestamp | | **completedAt** | `string` | optional | Execution completion timestamp | | **durationMs** | `integer` | optional | Total execution duration in milliseconds | +| **waitMs** | `integer` | optional | Total time the run spent suspended (waiting at a `screen`, `approval`, `wait` or other pausing node), summed over all its pauses, in milliseconds. Included in `durationMs`, which stays the total wall time, so the time spent executing is `durationMs - waitMs`. `0` on a run that never paused; on a `paused` entry, the wait up to the moment the entry was written. Absent when not recorded — a `missed` entry, or a run paused before this was tracked — which is not the same as zero. | | **runAs** | `Enum<'system' \| 'user'>` | optional | Execution context identity | | **tenantId** | `string` | optional | Tenant ID for multi-tenant isolation | diff --git a/packages/services/service-automation/src/run-wait-time.test.ts b/packages/services/service-automation/src/run-wait-time.test.ts new file mode 100644 index 00000000000..b43d4d37551 --- /dev/null +++ b/packages/services/service-automation/src/run-wait-time.test.ts @@ -0,0 +1,269 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #32284 — a run record says how much of its `durationMs` was WAITING. + * + * On the QA run a resumed screen flow reported `durationMs: 18691`, almost all + * of it the user's wait, and nothing on the record told an admin that. The + * maintainer's ruling (option A, comment 6879411530) adds one optional member, + * `ExecutionLog.waitMs`, and keeps `durationMs` the total wall time, so the + * time a run spent executing is `durationMs - waitMs`. + * + * What is pinned here, with the clock driven by hand (`vi.setSystemTime`, + * Date only — the engine's own `setTimeout`s keep running): every "work" node + * moves the clock by its own cost, and the test moves it between a pause and + * its resume, so each expected number is exact rather than a tolerance. + * + * 1. A run that never paused carries `waitMs: 0` — measured, not absent. + * 2. One pause: the record's `waitMs` is the time between the pause and the + * resume, and `durationMs - waitMs` is the time the nodes took. + * 3. Two pauses SUM, across two simulated restarts (three engines over one + * store), and each `paused` entry carries the wait up to its own moment. + * 4. A paused run cancelled where it waits: everything since the pause is + * wait. + * 5. The restore path: a resume that consumed the pause and then failed, an + * operator restore, and a later resume — the run's active time is the + * work its record shows, and the failed attempt plus the stranded time + * are wait, like the rest of the pause the restore re-armed. + * 6. A suspension that carries no clock (one parked before this release) + * resumes with `waitMs` NOT RECORDED — absent, never a guessed `0`. + * + * Every record is parsed through `ExecutionLogSchema`, so a member the spec + * did not declare would be stripped and the assertion would go red. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { defineActionDescriptor, ExecutionLogSchema } from '@objectstack/spec/automation'; +import { AutomationEngine, type NodeExecutor } from './engine.js'; +import { InMemorySuspendedRunStore } from './suspended-run-store.js'; + +const silent = { + info() {}, warn() {}, error() {}, debug() {}, + child() { return silent; }, +} as never; + +const T0 = Date.parse('2026-11-14T09:00:00.000Z'); + +/** Move the (Date-only) fake clock forward by `ms`. */ +const advance = (ms: number) => vi.setSystemTime(Date.now() + ms); + +const pauser: NodeExecutor = { + type: 'wait_for_user', + descriptor: defineActionDescriptor({ + type: 'wait_for_user', version: '1.0.0', name: 'wait_for_user', + supportsPause: true, resumeAuthority: 'any', + }), + async execute(node) { + return { success: true, suspend: true, correlation: `screen:${node.id}` }; + }, +}; + +/** A node whose execution costs `config.costMs` of wall time. */ +const work: NodeExecutor = { + type: 'work', + async execute(node) { + advance(Number((node.config as { costMs?: number } | undefined)?.costMs ?? 0)); + return { success: true }; + }, +}; + +/** Fails on its first execution and succeeds after — the strand-then-restore shape. */ +function flaky(): NodeExecutor { + let calls = 0; + return { + type: 'flaky_work', + async execute() { + advance(20); + calls += 1; + if (calls === 1) return { success: false, error: 'downstream row was locked' }; + return { success: true }; + }, + }; +} + +type Step = { id: string; type: string; costMs?: number }; + +/** A straight line start → …steps → end. */ +function line(name: string, steps: Step[]) { + const nodes = [ + { id: 'start', type: 'start', label: 'Start' }, + ...steps.map((s) => ({ + id: s.id, type: s.type, label: s.id, + ...(s.costMs === undefined ? {} : { config: { costMs: s.costMs } }), + })), + { id: 'end', type: 'end', label: 'End' }, + ]; + const edges = nodes.slice(1).map((n, i) => ({ id: `e${i}`, source: nodes[i].id, target: n.id })); + return { name, label: name, type: 'autolaunched', nodes, edges }; +} + +/** start → work(100) → ask (pause) → work(40) → confirm (pause) → work(7) → end */ +const TWO_SCREENS = line('two_screens', [ + { id: 'prepare', type: 'work', costMs: 100 }, + { id: 'ask', type: 'wait_for_user' }, + { id: 'apply', type: 'work', costMs: 40 }, + { id: 'confirm', type: 'wait_for_user' }, + { id: 'finish', type: 'work', costMs: 7 }, +]); + +function engineOver(store?: InMemorySuspendedRunStore, ...extra: NodeExecutor[]): AutomationEngine { + const engine = new AutomationEngine(silent, store); + for (const executor of [pauser, work, ...extra]) engine.registerNodeExecutor(executor); + engine.registerFlow('two_screens', TWO_SCREENS as never); + engine.registerFlow('one_screen', line('one_screen', [ + { id: 'prepare', type: 'work', costMs: 100 }, + { id: 'ask', type: 'wait_for_user' }, + { id: 'apply', type: 'work', costMs: 40 }, + ]) as never); + engine.registerFlow('no_screen', line('no_screen', [{ id: 'prepare', type: 'work', costMs: 100 }]) as never); + engine.registerFlow('screen_then_flaky', line('screen_then_flaky', [ + { id: 'prepare', type: 'work', costMs: 100 }, + { id: 'ask', type: 'wait_for_user' }, + { id: 'write_back', type: 'flaky_work' }, + ]) as never); + return engine; +} + +/** The run as `GET …/runs/:runId` serves it, through the published schema. */ +async function record(engine: AutomationEngine, runId: string) { + const run = await engine.getRun(runId); + expect(run, `run '${runId}' is recorded`).not.toBeNull(); + return ExecutionLogSchema.parse(run); +} + +describe('#32284 — ExecutionLog.waitMs: the part of durationMs a run spent suspended', () => { + beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(T0); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it('a run that never paused carries waitMs: 0 — a measured zero, not an absent field', async () => { + const engine = engineOver(); + const res = await engine.execute('no_screen'); + expect(res.success).toBe(true); + + const run = await record(engine, (await engine.listRuns('no_screen'))[0].id); + expect(run.status).toBe('completed'); + expect(run.durationMs).toBe(100); + expect(run.waitMs).toBe(0); + }); + + it('one pause: waitMs is the time between the pause and its resume, and durationMs - waitMs is the work', async () => { + const engine = engineOver(); + const paused = await engine.execute('one_screen'); + expect(paused.status).toBe('paused'); + const runId = paused.runId!; + + // The paused entry: the run's first pause, so nothing has waited yet. + const atPause = await record(engine, runId); + expect(atPause.status).toBe('paused'); + expect(atPause.durationMs).toBe(100); + expect(atPause.waitMs).toBe(0); + + advance(18_500); // the user fills the screen in + const done = await engine.resume(runId); + expect(done.success).toBe(true); + + const run = await record(engine, runId); + expect(run.status).toBe('completed'); + expect(run.durationMs).toBe(18_640); + expect(run.waitMs).toBe(18_500); + expect(run.durationMs! - run.waitMs!).toBe(140); // prepare 100 + apply 40 + }); + + it('two pauses SUM, across two restarts, and each paused entry carries the wait up to its own moment', async () => { + const store = new InMemorySuspendedRunStore(); + + const first = await engineOver(store).execute('two_screens'); + expect(first.status).toBe('paused'); + const runId = first.runId!; + + advance(5_000); + // A fresh engine over the same store — the process restarted while the + // run waited, so the clock must come back from the store, not memory. + const second = engineOver(store); + const repaused = await second.resume(runId); + expect(repaused.status).toBe('paused'); + const atSecondPause = await record(second, runId); + expect(atSecondPause.durationMs).toBe(5_140); + expect(atSecondPause.waitMs).toBe(5_000); + + advance(30_000); + const third = engineOver(store); + const done = await third.resume(runId); + expect(done.success).toBe(true); + + const run = await record(third, runId); + expect(run.status).toBe('completed'); + expect(run.waitMs).toBe(35_000); // 5 s + 30 s, not the last pause alone + expect(run.durationMs).toBe(35_147); + expect(run.durationMs! - run.waitMs!).toBe(147); // 100 + 40 + 7 + // The durable terminal record says the same, for a reader after a restart. + expect((await store.loadTerminal(runId))?.waitMs).toBe(35_000); + }); + + it('a paused run cancelled where it waits: everything since the pause is wait', async () => { + const engine = engineOver(); + const paused = await engine.execute('one_screen'); + advance(2_000); + expect(await engine.cancelRun(paused.runId!, 'nobody answered')).toBe(true); + + const run = await record(engine, paused.runId!); + expect(run.status).toBe('cancelled'); + expect(run.durationMs).toBe(2_100); + expect(run.waitMs).toBe(2_000); + }); + + it('the restore path: the re-armed pause keeps its clock, so the run\'s active time is the work its record shows', async () => { + const engine = engineOver(undefined, flaky()); + const paused = await engine.execute('screen_then_flaky'); + const runId = paused.runId!; + + advance(1_000); + const stranded = await engine.resume(runId); + expect(stranded.status).toBe('stranded'); + const failed = await record(engine, runId); + expect(failed.status).toBe('failed'); + expect(failed.durationMs).toBe(1_120); + expect(failed.waitMs).toBe(1_000); // the pause it consumed; the failed write is work + + advance(500); + const restored = await engine.restoreConsumedSuspension(runId, { requestedBy: 'ops', reason: 'row unlocked' }); + expect(restored.restored).toBe(true); + const reArmed = await record(engine, runId); + expect(reArmed.status).toBe('paused'); + expect(reArmed.durationMs).toBe(1_620); + expect(reArmed.waitMs).toBe(1_520); // all but the 100 ms it executed before the pause + + advance(2_000); + const done = await engine.resume(runId); + expect(done.success).toBe(true); + const run = await record(engine, runId); + expect(run.status).toBe('completed'); + expect(run.durationMs).toBe(3_640); + expect(run.waitMs).toBe(3_520); + expect(run.durationMs! - run.waitMs!).toBe(120); // prepare 100 + the write that landed 20 + }); + + it('a suspension that carries no clock resumes with waitMs NOT RECORDED — absent, never a guessed 0', async () => { + const store = new InMemorySuspendedRunStore(); + const paused = await engineOver(store).execute('one_screen'); + const runId = paused.runId!; + // A pause parked before this release: the same row, without the clock. + const parked = await store.load(runId); + expect(parked?.activeMs).toBe(100); // control: a pause recorded today HAS one + const { activeMs: _dropped, ...legacy } = parked!; + await store.save(legacy); + + advance(4_000); + const resumer = engineOver(store); + expect((await resumer.resume(runId)).success).toBe(true); + const run = await record(resumer, runId); + expect(run.status).toBe('completed'); + expect(run.durationMs).toBe(4_140); + expect(run.waitMs).toBeUndefined(); + }); +}); diff --git a/packages/services/service-automation/src/suspended-run-store.test.ts b/packages/services/service-automation/src/suspended-run-store.test.ts index 246d0cd9dba..4a1f1d80ef8 100644 --- a/packages/services/service-automation/src/suspended-run-store.test.ts +++ b/packages/services/service-automation/src/suspended-run-store.test.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { AutomationEngine } from './engine.js'; import { ObjectStoreSuspendedRunStore, type SuspendedRunStoreEngine } from './suspended-run-store.js'; import type { RunRecord, SuspendedRun } from './engine.js'; @@ -1578,3 +1578,134 @@ describe('#20725 the parked-run read behind the §7.3 disable guard asks for the expect(thrown.message).toContain(`'${runId}'`); }); }); + +// ─── The wait clock on the row (#32284) ────────────────────────────────────── +// +// `ExecutionLog.waitMs` is only as good as the row that carries the clock +// across a restart: a screen flow's user typically answers long after the +// process that parked the run is gone. So these pins drive the REAL engine +// across fresh instances over one table and read the cells, as the +// trigger-attribution and refusal groups above do: a mapper that never wrote a +// column but happened to rebuild the value from memory would pass a +// `loadTerminal` assertion and fail the cell one. +describe('ObjectStoreSuspendedRunStore — the wait clock survives the restart (#32284)', () => { + const T0 = Date.parse('2026-11-14T09:00:00.000Z'); + const advance = (ms: number) => vi.setSystemTime(Date.now() + ms); + const settle = () => new Promise((r) => setImmediate(r)); + + beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(T0); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + /** start → prepare (100 ms) → ask (pause) → apply (40 ms) → confirm (pause) → end, over `table`. */ + function twoPauseEngine(table: ReturnType, options: { failFirstApply?: boolean } = {}) { + const e = new AutomationEngine(createTestLogger(), new ObjectStoreSuspendedRunStore(table, createTestLogger())); + e.registerNodeExecutor({ + type: 'pause_node', + descriptor: PAUSE_NODE_DESCRIPTOR, + async execute(node) { return { success: true, suspend: true, correlation: `screen:${node.id}` }; }, + }); + let applies = 0; + e.registerNodeExecutor({ + type: 'work', + async execute(node) { + advance(node.id === 'prepare' ? 100 : 40); + if (node.id === 'apply' && options.failFirstApply && ++applies === 1) { + return { success: false, error: 'downstream row was locked' }; + } + return { success: true }; + }, + }); + e.registerFlow('two_pause_flow', { + name: 'two_pause_flow', label: 'Two Pause Flow', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'prepare', type: 'work', label: 'Prepare' }, + { id: 'ask', type: 'pause_node', label: 'Ask' }, + { id: 'apply', type: 'work', label: 'Apply' }, + { id: 'confirm', type: 'pause_node', label: 'Confirm' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'prepare' }, + { id: 'e2', source: 'prepare', target: 'ask' }, + { id: 'e3', source: 'ask', target: 'apply' }, + { id: 'e4', source: 'apply', target: 'confirm' }, + { id: 'e5', source: 'confirm', target: 'end' }, + ], + } as never); + return e; + } + + it('writes active_ms on each paused row and the summed wait_ms on the terminal row, read back by a fresh engine', async () => { + const table = createFakeEngine(); + const runId = (await twoPauseEngine(table).execute('two_pause_flow')).runId!; + expect(table.rows.get(runId)).toMatchObject({ status: 'paused', node_id: 'ask', active_ms: 100 }); + + advance(5_000); + expect((await twoPauseEngine(table).resume(runId)).status).toBe('paused'); + // The clock written forward: 140 ms executed, 5 s waited. + expect(table.rows.get(runId)).toMatchObject({ status: 'paused', node_id: 'confirm', active_ms: 140 }); + + advance(30_000); + expect((await twoPauseEngine(table).resume(runId)).success).toBe(true); + await settle(); + + const terminal = [...table.rows.values()].find((r) => r.status === 'completed'); + expect(terminal).toMatchObject({ duration_ms: 35_140, wait_ms: 35_000 }); + + // A process that never saw the run answers from the row alone. + const run = await twoPauseEngine(table).getRun(runId); + expect(run).toMatchObject({ status: 'completed', durationMs: 35_140, waitMs: 35_000 }); + }); + + it('a stranded row keeps the consumed pause\'s clock, so a restore after a restart still sums every pause', async () => { + const table = createFakeEngine(); + const runId = (await twoPauseEngine(table, { failFirstApply: true }).execute('two_pause_flow')).runId!; + + advance(1_000); + expect((await twoPauseEngine(table, { failFirstApply: true }).resume(runId)).status).toBe('stranded'); + await settle(); + const stranded = [...table.rows.values()].find((r) => r.status === 'failed'); + // `wait_ms` is the failed record's own; `active_ms` is the consumed pause's. + expect(stranded).toMatchObject({ duration_ms: 1_140, wait_ms: 1_000, active_ms: 100 }); + + advance(500); + // A fresh process: no journal, only the row — the restore reads the clock from it. + expect((await twoPauseEngine(table).restoreConsumedSuspension(runId)).restored).toBe(true); + expect(table.rows.get(runId)).toMatchObject({ status: 'paused', node_id: 'ask', active_ms: 100 }); + + advance(2_000); + expect((await twoPauseEngine(table).resume(runId)).status).toBe('paused'); + advance(10_000); + expect((await twoPauseEngine(table).resume(runId)).success).toBe(true); + await settle(); + const run = await twoPauseEngine(table).getRun(runId); + // Active: prepare 100 + the apply that landed 40. Wait: the first pause + // as the restore re-armed it (3 540 ms, the failed attempt and the + // stranded time included) plus the second pause (10 s). + expect(run).toMatchObject({ status: 'completed', durationMs: 13_680, waitMs: 13_540 }); + }); + + it('a row written before the columns existed reads waitMs NOT RECORDED, never 0', async () => { + const table = createFakeEngine(); + const store = new ObjectStoreSuspendedRunStore(table, createTestLogger()); + await store.recordTerminal({ + runId: 'legacy_run', flowName: 'two_pause_flow', status: 'completed', + startedAt: '2026-11-01T00:00:00.000Z', finishedAt: '2026-11-01T00:00:18.691Z', durationMs: 18_691, + }); + const row = [...table.rows.values()][0]; + delete row.wait_ms; // the column as an older schema left it: absent + const reread = await new ObjectStoreSuspendedRunStore(table, createTestLogger()).loadTerminal('legacy_run'); + expect(reread?.durationMs).toBe(18_691); + expect(reread?.waitMs).toBeUndefined(); + + await store.save(baseRun()); // a paused row with no clock + expect(table.rows.get('run_abc')?.active_ms).toBeNull(); + expect((await store.load('run_abc'))?.activeMs).toBeUndefined(); + }); +}); diff --git a/packages/spec/authorable-surface/automation.json b/packages/spec/authorable-surface/automation.json index c34a30827a5..7fe59977225 100644 --- a/packages/spec/authorable-surface/automation.json +++ b/packages/spec/authorable-surface/automation.json @@ -157,6 +157,7 @@ "automation/ExecutionLog:tenantId", "automation/ExecutionLog:trigger", "automation/ExecutionLog:variables", + "automation/ExecutionLog:waitMs", "automation/ExecutionStepLog:branch", "automation/ExecutionStepLog:completedAt", "automation/ExecutionStepLog:droppedFields",