Skip to content

Commit 50c4166

Browse files
committed
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 <noreply@anthropic.com>
1 parent df29270 commit 50c4166

6 files changed

Lines changed: 421 additions & 1 deletion

File tree

‎.changeset/32284-run-wait-ms.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/service-automation': minor
4+
---
5+
6+
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
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: added
10+
11+
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.
12+
13+
`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.
14+
15+
`@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.
16+
17+
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.

‎content/docs/references/api/automation-api.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -937,6 +937,7 @@ const result = AutomationApiErrorCode.parse(data);
937937
| **startedAt** | `string` | ✅ | Execution start timestamp |
938938
| **completedAt** | `string` | optional | Execution completion timestamp |
939939
| **durationMs** | `integer` | optional | Total execution duration in milliseconds |
940+
| **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. |
940941
| **runAs** | `Enum<'system' \| 'user'>` | optional | Execution context identity |
941942
| **tenantId** | `string` | optional | Tenant ID for multi-tenant isolation |
942943

‎content/docs/references/automation/execution.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ const result = CheckpointSchema.parse(data);
113113
| **startedAt** | `string` | ✅ | Execution start timestamp |
114114
| **completedAt** | `string` | optional | Execution completion timestamp |
115115
| **durationMs** | `integer` | optional | Total execution duration in milliseconds |
116+
| **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. |
116117
| **runAs** | `Enum<'system' \| 'user'>` | optional | Execution context identity |
117118
| **tenantId** | `string` | optional | Tenant ID for multi-tenant isolation |
118119

Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,269 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #32284 — a run record says how much of its `durationMs` was WAITING.
5+
*
6+
* On the QA run a resumed screen flow reported `durationMs: 18691`, almost all
7+
* of it the user's wait, and nothing on the record told an admin that. The
8+
* maintainer's ruling (option A, comment 6879411530) adds one optional member,
9+
* `ExecutionLog.waitMs`, and keeps `durationMs` the total wall time, so the
10+
* time a run spent executing is `durationMs - waitMs`.
11+
*
12+
* What is pinned here, with the clock driven by hand (`vi.setSystemTime`,
13+
* Date only — the engine's own `setTimeout`s keep running): every "work" node
14+
* moves the clock by its own cost, and the test moves it between a pause and
15+
* its resume, so each expected number is exact rather than a tolerance.
16+
*
17+
* 1. A run that never paused carries `waitMs: 0` — measured, not absent.
18+
* 2. One pause: the record's `waitMs` is the time between the pause and the
19+
* resume, and `durationMs - waitMs` is the time the nodes took.
20+
* 3. Two pauses SUM, across two simulated restarts (three engines over one
21+
* store), and each `paused` entry carries the wait up to its own moment.
22+
* 4. A paused run cancelled where it waits: everything since the pause is
23+
* wait.
24+
* 5. The restore path: a resume that consumed the pause and then failed, an
25+
* operator restore, and a later resume — the run's active time is the
26+
* work its record shows, and the failed attempt plus the stranded time
27+
* are wait, like the rest of the pause the restore re-armed.
28+
* 6. A suspension that carries no clock (one parked before this release)
29+
* resumes with `waitMs` NOT RECORDED — absent, never a guessed `0`.
30+
*
31+
* Every record is parsed through `ExecutionLogSchema`, so a member the spec
32+
* did not declare would be stripped and the assertion would go red.
33+
*/
34+
35+
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
36+
import { defineActionDescriptor, ExecutionLogSchema } from '@objectstack/spec/automation';
37+
import { AutomationEngine, type NodeExecutor } from './engine.js';
38+
import { InMemorySuspendedRunStore } from './suspended-run-store.js';
39+
40+
const silent = {
41+
info() {}, warn() {}, error() {}, debug() {},
42+
child() { return silent; },
43+
} as never;
44+
45+
const T0 = Date.parse('2026-11-14T09:00:00.000Z');
46+
47+
/** Move the (Date-only) fake clock forward by `ms`. */
48+
const advance = (ms: number) => vi.setSystemTime(Date.now() + ms);
49+
50+
const pauser: NodeExecutor = {
51+
type: 'wait_for_user',
52+
descriptor: defineActionDescriptor({
53+
type: 'wait_for_user', version: '1.0.0', name: 'wait_for_user',
54+
supportsPause: true, resumeAuthority: 'any',
55+
}),
56+
async execute(node) {
57+
return { success: true, suspend: true, correlation: `screen:${node.id}` };
58+
},
59+
};
60+
61+
/** A node whose execution costs `config.costMs` of wall time. */
62+
const work: NodeExecutor = {
63+
type: 'work',
64+
async execute(node) {
65+
advance(Number((node.config as { costMs?: number } | undefined)?.costMs ?? 0));
66+
return { success: true };
67+
},
68+
};
69+
70+
/** Fails on its first execution and succeeds after — the strand-then-restore shape. */
71+
function flaky(): NodeExecutor {
72+
let calls = 0;
73+
return {
74+
type: 'flaky_work',
75+
async execute() {
76+
advance(20);
77+
calls += 1;
78+
if (calls === 1) return { success: false, error: 'downstream row was locked' };
79+
return { success: true };
80+
},
81+
};
82+
}
83+
84+
type Step = { id: string; type: string; costMs?: number };
85+
86+
/** A straight line start → …steps → end. */
87+
function line(name: string, steps: Step[]) {
88+
const nodes = [
89+
{ id: 'start', type: 'start', label: 'Start' },
90+
...steps.map((s) => ({
91+
id: s.id, type: s.type, label: s.id,
92+
...(s.costMs === undefined ? {} : { config: { costMs: s.costMs } }),
93+
})),
94+
{ id: 'end', type: 'end', label: 'End' },
95+
];
96+
const edges = nodes.slice(1).map((n, i) => ({ id: `e${i}`, source: nodes[i].id, target: n.id }));
97+
return { name, label: name, type: 'autolaunched', nodes, edges };
98+
}
99+
100+
/** start → work(100) → ask (pause) → work(40) → confirm (pause) → work(7) → end */
101+
const TWO_SCREENS = line('two_screens', [
102+
{ id: 'prepare', type: 'work', costMs: 100 },
103+
{ id: 'ask', type: 'wait_for_user' },
104+
{ id: 'apply', type: 'work', costMs: 40 },
105+
{ id: 'confirm', type: 'wait_for_user' },
106+
{ id: 'finish', type: 'work', costMs: 7 },
107+
]);
108+
109+
function engineOver(store?: InMemorySuspendedRunStore, ...extra: NodeExecutor[]): AutomationEngine {
110+
const engine = new AutomationEngine(silent, store);
111+
for (const executor of [pauser, work, ...extra]) engine.registerNodeExecutor(executor);
112+
engine.registerFlow('two_screens', TWO_SCREENS as never);
113+
engine.registerFlow('one_screen', line('one_screen', [
114+
{ id: 'prepare', type: 'work', costMs: 100 },
115+
{ id: 'ask', type: 'wait_for_user' },
116+
{ id: 'apply', type: 'work', costMs: 40 },
117+
]) as never);
118+
engine.registerFlow('no_screen', line('no_screen', [{ id: 'prepare', type: 'work', costMs: 100 }]) as never);
119+
engine.registerFlow('screen_then_flaky', line('screen_then_flaky', [
120+
{ id: 'prepare', type: 'work', costMs: 100 },
121+
{ id: 'ask', type: 'wait_for_user' },
122+
{ id: 'write_back', type: 'flaky_work' },
123+
]) as never);
124+
return engine;
125+
}
126+
127+
/** The run as `GET …/runs/:runId` serves it, through the published schema. */
128+
async function record(engine: AutomationEngine, runId: string) {
129+
const run = await engine.getRun(runId);
130+
expect(run, `run '${runId}' is recorded`).not.toBeNull();
131+
return ExecutionLogSchema.parse(run);
132+
}
133+
134+
describe('#32284 — ExecutionLog.waitMs: the part of durationMs a run spent suspended', () => {
135+
beforeEach(() => {
136+
vi.useFakeTimers({ toFake: ['Date'] });
137+
vi.setSystemTime(T0);
138+
});
139+
afterEach(() => {
140+
vi.useRealTimers();
141+
});
142+
143+
it('a run that never paused carries waitMs: 0 — a measured zero, not an absent field', async () => {
144+
const engine = engineOver();
145+
const res = await engine.execute('no_screen');
146+
expect(res.success).toBe(true);
147+
148+
const run = await record(engine, (await engine.listRuns('no_screen'))[0].id);
149+
expect(run.status).toBe('completed');
150+
expect(run.durationMs).toBe(100);
151+
expect(run.waitMs).toBe(0);
152+
});
153+
154+
it('one pause: waitMs is the time between the pause and its resume, and durationMs - waitMs is the work', async () => {
155+
const engine = engineOver();
156+
const paused = await engine.execute('one_screen');
157+
expect(paused.status).toBe('paused');
158+
const runId = paused.runId!;
159+
160+
// The paused entry: the run's first pause, so nothing has waited yet.
161+
const atPause = await record(engine, runId);
162+
expect(atPause.status).toBe('paused');
163+
expect(atPause.durationMs).toBe(100);
164+
expect(atPause.waitMs).toBe(0);
165+
166+
advance(18_500); // the user fills the screen in
167+
const done = await engine.resume(runId);
168+
expect(done.success).toBe(true);
169+
170+
const run = await record(engine, runId);
171+
expect(run.status).toBe('completed');
172+
expect(run.durationMs).toBe(18_640);
173+
expect(run.waitMs).toBe(18_500);
174+
expect(run.durationMs! - run.waitMs!).toBe(140); // prepare 100 + apply 40
175+
});
176+
177+
it('two pauses SUM, across two restarts, and each paused entry carries the wait up to its own moment', async () => {
178+
const store = new InMemorySuspendedRunStore();
179+
180+
const first = await engineOver(store).execute('two_screens');
181+
expect(first.status).toBe('paused');
182+
const runId = first.runId!;
183+
184+
advance(5_000);
185+
// A fresh engine over the same store — the process restarted while the
186+
// run waited, so the clock must come back from the store, not memory.
187+
const second = engineOver(store);
188+
const repaused = await second.resume(runId);
189+
expect(repaused.status).toBe('paused');
190+
const atSecondPause = await record(second, runId);
191+
expect(atSecondPause.durationMs).toBe(5_140);
192+
expect(atSecondPause.waitMs).toBe(5_000);
193+
194+
advance(30_000);
195+
const third = engineOver(store);
196+
const done = await third.resume(runId);
197+
expect(done.success).toBe(true);
198+
199+
const run = await record(third, runId);
200+
expect(run.status).toBe('completed');
201+
expect(run.waitMs).toBe(35_000); // 5 s + 30 s, not the last pause alone
202+
expect(run.durationMs).toBe(35_147);
203+
expect(run.durationMs! - run.waitMs!).toBe(147); // 100 + 40 + 7
204+
// The durable terminal record says the same, for a reader after a restart.
205+
expect((await store.loadTerminal(runId))?.waitMs).toBe(35_000);
206+
});
207+
208+
it('a paused run cancelled where it waits: everything since the pause is wait', async () => {
209+
const engine = engineOver();
210+
const paused = await engine.execute('one_screen');
211+
advance(2_000);
212+
expect(await engine.cancelRun(paused.runId!, 'nobody answered')).toBe(true);
213+
214+
const run = await record(engine, paused.runId!);
215+
expect(run.status).toBe('cancelled');
216+
expect(run.durationMs).toBe(2_100);
217+
expect(run.waitMs).toBe(2_000);
218+
});
219+
220+
it('the restore path: the re-armed pause keeps its clock, so the run\'s active time is the work its record shows', async () => {
221+
const engine = engineOver(undefined, flaky());
222+
const paused = await engine.execute('screen_then_flaky');
223+
const runId = paused.runId!;
224+
225+
advance(1_000);
226+
const stranded = await engine.resume(runId);
227+
expect(stranded.status).toBe('stranded');
228+
const failed = await record(engine, runId);
229+
expect(failed.status).toBe('failed');
230+
expect(failed.durationMs).toBe(1_120);
231+
expect(failed.waitMs).toBe(1_000); // the pause it consumed; the failed write is work
232+
233+
advance(500);
234+
const restored = await engine.restoreConsumedSuspension(runId, { requestedBy: 'ops', reason: 'row unlocked' });
235+
expect(restored.restored).toBe(true);
236+
const reArmed = await record(engine, runId);
237+
expect(reArmed.status).toBe('paused');
238+
expect(reArmed.durationMs).toBe(1_620);
239+
expect(reArmed.waitMs).toBe(1_520); // all but the 100 ms it executed before the pause
240+
241+
advance(2_000);
242+
const done = await engine.resume(runId);
243+
expect(done.success).toBe(true);
244+
const run = await record(engine, runId);
245+
expect(run.status).toBe('completed');
246+
expect(run.durationMs).toBe(3_640);
247+
expect(run.waitMs).toBe(3_520);
248+
expect(run.durationMs! - run.waitMs!).toBe(120); // prepare 100 + the write that landed 20
249+
});
250+
251+
it('a suspension that carries no clock resumes with waitMs NOT RECORDED — absent, never a guessed 0', async () => {
252+
const store = new InMemorySuspendedRunStore();
253+
const paused = await engineOver(store).execute('one_screen');
254+
const runId = paused.runId!;
255+
// A pause parked before this release: the same row, without the clock.
256+
const parked = await store.load(runId);
257+
expect(parked?.activeMs).toBe(100); // control: a pause recorded today HAS one
258+
const { activeMs: _dropped, ...legacy } = parked!;
259+
await store.save(legacy);
260+
261+
advance(4_000);
262+
const resumer = engineOver(store);
263+
expect((await resumer.resume(runId)).success).toBe(true);
264+
const run = await record(resumer, runId);
265+
expect(run.status).toBe('completed');
266+
expect(run.durationMs).toBe(4_140);
267+
expect(run.waitMs).toBeUndefined();
268+
});
269+
});

0 commit comments

Comments
 (0)