@proofoftech/flowsafe 0.34.0 → 0.35.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/CHANGELOG.md +42 -0
- package/README.md +1 -1
- package/dist/do-runner/schedule-source.d.ts +4 -3
- package/dist/do-runner/schedule-source.d.ts.map +1 -1
- package/dist/do-runner/schedule-source.js.map +1 -1
- package/dist/schedules/fire-plan.d.ts +30 -0
- package/dist/schedules/fire-plan.d.ts.map +1 -0
- package/dist/schedules/fire-plan.js +111 -0
- package/dist/schedules/fire-plan.js.map +1 -0
- package/dist/schedules/index.d.ts +4 -2
- package/dist/schedules/index.d.ts.map +1 -1
- package/dist/schedules/index.js +2 -0
- package/dist/schedules/index.js.map +1 -1
- package/dist/schedules/mutation-contract.d.ts +8 -6
- package/dist/schedules/mutation-contract.d.ts.map +1 -1
- package/dist/schedules/mutation-contract.js.map +1 -1
- package/dist/schedules/router.d.ts +9 -6
- package/dist/schedules/router.d.ts.map +1 -1
- package/dist/schedules/router.js +362 -94
- package/dist/schedules/router.js.map +1 -1
- package/dist/schedules/schedule-extensions.d.ts +46 -0
- package/dist/schedules/schedule-extensions.d.ts.map +1 -0
- package/dist/schedules/schedule-extensions.js +7 -0
- package/dist/schedules/schedule-extensions.js.map +1 -0
- package/dist/schedules/schedules-d1.d.ts +44 -10
- package/dist/schedules/schedules-d1.d.ts.map +1 -1
- package/dist/schedules/schedules-d1.js +437 -68
- package/dist/schedules/schedules-d1.js.map +1 -1
- package/dist/schedules/tick.d.ts +81 -18
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +701 -168
- package/dist/schedules/tick.js.map +1 -1
- package/package.json +1 -1
package/dist/schedules/tick.js
CHANGED
|
@@ -28,10 +28,12 @@ import { assertMutationEpoch, isRunStartPendingError, normalizeMutationEpoch, }
|
|
|
28
28
|
// from the prepared trigger snapshot. RunnerRuntime merges it below
|
|
29
29
|
// provider/runtime-derived values rather than trusting a forwarded body copy.
|
|
30
30
|
import { ScheduleInputSchema } from '@mastra/core/schedules';
|
|
31
|
-
import { computeNextFireAt } from '@mastra/core/workflows';
|
|
32
31
|
import { admitsWorkAuthoring, isPathSafeId, isReservedExecutionContextKey, RESERVED_EXECUTION_CONTEXT_KEYS, readExecutionFence, resolveScheduleStartOwner, stripReservedExecutionContext, } from '../do-runner/index.js';
|
|
33
32
|
import { exceedsDepth, exceedsRunInputDepth, MAX_RUN_INPUT_DEPTH, runInputDepthMessage, } from '../do-runner/run-input-depth.js';
|
|
34
|
-
import {
|
|
33
|
+
import { isTerminalRunStatus } from '../do-runner/run-terminal-state.js';
|
|
34
|
+
import { nonnegativeSafeInteger, positiveSafeInteger, } from '../numeric-config.js';
|
|
35
|
+
import { planScheduleFire, previewScheduleFires, } from './fire-plan.js';
|
|
36
|
+
import { SCHEDULE_ADMISSION_MAX_RETRIES, } from './schedule-extensions.js';
|
|
35
37
|
import { parseScheduleAgentDispatchReceipt, } from './schedules-d1.js';
|
|
36
38
|
import { scheduleCreatorRole, } from './target-policy.js';
|
|
37
39
|
/**
|
|
@@ -315,30 +317,45 @@ function dispatchIdentifiers(ref) {
|
|
|
315
317
|
const { agentTarget: _target, ...identifiers } = ref;
|
|
316
318
|
return identifiers;
|
|
317
319
|
}
|
|
320
|
+
function storedScheduleOrigin(trigger) {
|
|
321
|
+
const origin = contextObject(trigger.metadata?.scheduleOrigin);
|
|
322
|
+
if (origin?.id === trigger.scheduleId &&
|
|
323
|
+
origin.scheduledFireAt === trigger.scheduledFireAt &&
|
|
324
|
+
(origin.timing === 'cron' || origin.timing === 'at')) {
|
|
325
|
+
return origin;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
318
328
|
/**
|
|
319
329
|
* Resolve the canonical target snapshot bound to one atomically claimed fire.
|
|
320
330
|
* A reusable schedule id alone never authorizes a start.
|
|
321
331
|
*/
|
|
322
332
|
export function createScheduleStartSource(store) {
|
|
333
|
+
const resolve = async (scheduleId, dispatchId, runId) => {
|
|
334
|
+
const trigger = await store.getClaimedScheduleDispatch(scheduleId, dispatchId, runId);
|
|
335
|
+
const metadata = trigger?.metadata;
|
|
336
|
+
if (trigger?.id !== dispatchId ||
|
|
337
|
+
trigger.scheduleId !== scheduleId ||
|
|
338
|
+
trigger.runId !== runId ||
|
|
339
|
+
trigger.outcome !== 'deferred' ||
|
|
340
|
+
!metadata ||
|
|
341
|
+
!['prepared', 'executing', 'settled'].includes(String(metadata.dispatchState))) {
|
|
342
|
+
return undefined;
|
|
343
|
+
}
|
|
344
|
+
const ref = scheduleTickDispatchRef(metadata.dispatchRef);
|
|
345
|
+
if (!ref ||
|
|
346
|
+
ref.scheduleId !== scheduleId ||
|
|
347
|
+
ref.dispatchId !== dispatchId ||
|
|
348
|
+
ref.runId !== runId) {
|
|
349
|
+
return undefined;
|
|
350
|
+
}
|
|
351
|
+
return { trigger, ref };
|
|
352
|
+
};
|
|
323
353
|
return {
|
|
324
354
|
async resolveScheduleTarget(scheduleId, dispatchId, runId) {
|
|
325
|
-
const
|
|
326
|
-
|
|
327
|
-
if (trigger?.id !== dispatchId ||
|
|
328
|
-
trigger.scheduleId !== scheduleId ||
|
|
329
|
-
trigger.runId !== runId ||
|
|
330
|
-
trigger.outcome !== 'deferred' ||
|
|
331
|
-
!metadata ||
|
|
332
|
-
!['prepared', 'executing', 'settled'].includes(String(metadata.dispatchState))) {
|
|
355
|
+
const resolved = await resolve(scheduleId, dispatchId, runId);
|
|
356
|
+
if (!resolved)
|
|
333
357
|
return undefined;
|
|
334
|
-
}
|
|
335
|
-
const ref = scheduleTickDispatchRef(metadata.dispatchRef);
|
|
336
|
-
if (!ref ||
|
|
337
|
-
ref.scheduleId !== scheduleId ||
|
|
338
|
-
ref.dispatchId !== dispatchId ||
|
|
339
|
-
ref.runId !== runId) {
|
|
340
|
-
return undefined;
|
|
341
|
-
}
|
|
358
|
+
const { ref } = resolved;
|
|
342
359
|
return ref.target === 'workflow'
|
|
343
360
|
? ref.workflowTarget
|
|
344
361
|
: {
|
|
@@ -346,6 +363,10 @@ export function createScheduleStartSource(store) {
|
|
|
346
363
|
providerOptions: agentScheduleProviderOptions(scheduleId, ref.agentTarget),
|
|
347
364
|
};
|
|
348
365
|
},
|
|
366
|
+
async resolveScheduleOrigin(scheduleId, dispatchId, runId) {
|
|
367
|
+
const resolved = await resolve(scheduleId, dispatchId, runId);
|
|
368
|
+
return resolved && storedScheduleOrigin(resolved.trigger);
|
|
369
|
+
},
|
|
349
370
|
};
|
|
350
371
|
}
|
|
351
372
|
function statusOf(error) {
|
|
@@ -394,6 +415,65 @@ function outcomeCounter(outcome) {
|
|
|
394
415
|
? 'skipped'
|
|
395
416
|
: 'fired';
|
|
396
417
|
}
|
|
418
|
+
const DEADLINE_EXPIRED = Symbol('deadline-expired');
|
|
419
|
+
async function withDeadline(call, deadline) {
|
|
420
|
+
if (performance.now() >= deadline)
|
|
421
|
+
return DEADLINE_EXPIRED;
|
|
422
|
+
let timer;
|
|
423
|
+
try {
|
|
424
|
+
const expired = new Promise((resolve) => {
|
|
425
|
+
const expire = () => {
|
|
426
|
+
const remaining = deadline - performance.now();
|
|
427
|
+
if (remaining <= 0) {
|
|
428
|
+
resolve(DEADLINE_EXPIRED);
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
// Timers backed by a signed 32-bit delay wrap or shorten larger values.
|
|
432
|
+
timer = setTimeout(expire, Math.min(Math.ceil(remaining), 2_147_483_647));
|
|
433
|
+
};
|
|
434
|
+
expire();
|
|
435
|
+
});
|
|
436
|
+
const value = await Promise.race([call(), expired]);
|
|
437
|
+
return performance.now() < deadline ? value : DEADLINE_EXPIRED;
|
|
438
|
+
}
|
|
439
|
+
finally {
|
|
440
|
+
if (timer !== undefined)
|
|
441
|
+
clearTimeout(timer);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
function normalizeAdmission(value) {
|
|
445
|
+
const decision = contextObject(value);
|
|
446
|
+
if (!decision)
|
|
447
|
+
return undefined;
|
|
448
|
+
const { admit } = decision;
|
|
449
|
+
if (admit === true)
|
|
450
|
+
return { admit: true };
|
|
451
|
+
const { reason, pause, retryAt } = decision;
|
|
452
|
+
if (admit !== false ||
|
|
453
|
+
typeof reason !== 'string' ||
|
|
454
|
+
(pause !== undefined && typeof pause !== 'boolean') ||
|
|
455
|
+
(retryAt !== undefined &&
|
|
456
|
+
(typeof retryAt !== 'number' || !Number.isFinite(retryAt)))) {
|
|
457
|
+
return undefined;
|
|
458
|
+
}
|
|
459
|
+
return {
|
|
460
|
+
admit: false,
|
|
461
|
+
reason: reason.length === 0 || reason.length > 64 || /[^a-z0-9._:-]/u.test(reason)
|
|
462
|
+
? 'admission-invalid-reason'
|
|
463
|
+
: reason,
|
|
464
|
+
...(pause === undefined ? {} : { pause }),
|
|
465
|
+
...(retryAt === undefined ? {} : { retryAt: Math.round(retryAt) }),
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
function scheduleAdmissionTarget(target) {
|
|
469
|
+
return target.type === 'agent'
|
|
470
|
+
? {
|
|
471
|
+
kind: 'agent',
|
|
472
|
+
agentId: target.agentId,
|
|
473
|
+
...(target.threadId === undefined ? {} : { threadId: target.threadId }),
|
|
474
|
+
}
|
|
475
|
+
: { kind: 'workflow', workflowId: target.workflowId };
|
|
476
|
+
}
|
|
397
477
|
/**
|
|
398
478
|
* Build the schedule tick: a `() => Promise<ScheduleTickResult>` a host slots
|
|
399
479
|
* into its alarm dispatch as its OWN failure-isolated duty (own try/catch, own
|
|
@@ -402,9 +482,18 @@ function outcomeCounter(outcome) {
|
|
|
402
482
|
* rest still fire.
|
|
403
483
|
*/
|
|
404
484
|
export function createScheduleTick(options) {
|
|
405
|
-
const { store, start } = options;
|
|
485
|
+
const { store, start, admit, defaultOverlapPolicy } = options;
|
|
486
|
+
if (defaultOverlapPolicy !== undefined &&
|
|
487
|
+
defaultOverlapPolicy !== 'allow' &&
|
|
488
|
+
defaultOverlapPolicy !== 'skip' &&
|
|
489
|
+
defaultOverlapPolicy !== 'queue_one') {
|
|
490
|
+
throw new RangeError('defaultOverlapPolicy must be allow, skip, or queue_one');
|
|
491
|
+
}
|
|
406
492
|
const now = options.now ?? Date.now;
|
|
407
493
|
const limit = nonnegativeSafeInteger(options.limit ?? 100, 'schedule tick limit');
|
|
494
|
+
const admitTimeoutMs = positiveSafeInteger(options.admitTimeoutMs ?? 5_000, 'schedule tick admission timeout');
|
|
495
|
+
const statusTimeoutMs = positiveSafeInteger(options.statusTimeoutMs ?? 5_000, 'schedule tick overlap status timeout');
|
|
496
|
+
const passBudgetMs = positiveSafeInteger(options.passBudgetMs ?? 30_000, 'schedule tick pass budget');
|
|
408
497
|
const audit = async (event) => {
|
|
409
498
|
if (!options.audit)
|
|
410
499
|
return;
|
|
@@ -503,6 +592,7 @@ export function createScheduleTick(options) {
|
|
|
503
592
|
*/
|
|
504
593
|
const settleMalformedDispatch = async (trigger, result, error = 'stored deferred dispatch is malformed', recorded = {}, target) => {
|
|
505
594
|
const runId = trigger.runId ?? undefined;
|
|
595
|
+
const jitterOffsetMs = trigger.metadata?.jitterOffsetMs;
|
|
506
596
|
try {
|
|
507
597
|
await store.recordTrigger({
|
|
508
598
|
...trigger,
|
|
@@ -510,6 +600,7 @@ export function createScheduleTick(options) {
|
|
|
510
600
|
error,
|
|
511
601
|
metadata: triggerMetadata({
|
|
512
602
|
reason: 'invalid-deferred-dispatch',
|
|
603
|
+
...(typeof jitterOffsetMs === 'number' ? { jitterOffsetMs } : {}),
|
|
513
604
|
...recorded,
|
|
514
605
|
}),
|
|
515
606
|
});
|
|
@@ -611,6 +702,12 @@ export function createScheduleTick(options) {
|
|
|
611
702
|
const receipt = await options.signalAgent({
|
|
612
703
|
...(mutationEpoch === undefined ? {} : { mutationEpoch }),
|
|
613
704
|
scheduleId: ref.scheduleId,
|
|
705
|
+
// Legacy deferred signals have a scheduled time and cron timing.
|
|
706
|
+
schedule: storedScheduleOrigin(trigger) ?? {
|
|
707
|
+
id: ref.scheduleId,
|
|
708
|
+
scheduledFireAt: trigger.scheduledFireAt,
|
|
709
|
+
timing: 'cron',
|
|
710
|
+
},
|
|
614
711
|
target: ref.agentTarget,
|
|
615
712
|
...(options.deploymentTag !== undefined
|
|
616
713
|
? { deploymentTag: options.deploymentTag }
|
|
@@ -736,29 +833,184 @@ export function createScheduleTick(options) {
|
|
|
736
833
|
return false;
|
|
737
834
|
}
|
|
738
835
|
};
|
|
739
|
-
const
|
|
740
|
-
const storedTarget = schedule.target;
|
|
836
|
+
const targetPreflight = (scheduleId, storedTarget, creatorRole) => {
|
|
741
837
|
const { type: targetKind } = storedTarget;
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
// mask by advancing to an arbitrary time); audit the failure and move on.
|
|
748
|
-
// The row therefore stays due and every later pass selects it again, holding
|
|
749
|
-
// a slot of the bounded page until an operator repairs or removes it. The
|
|
750
|
-
// audit event is the record this branch writes: the trigger receipt belongs
|
|
751
|
-
// to the CAS claim below, which the branch returns before reaching.
|
|
752
|
-
let newNextFireAt;
|
|
838
|
+
if (targetKind !== 'workflow' && targetKind !== 'agent') {
|
|
839
|
+
const reason = 'unknown-target-kind';
|
|
840
|
+
return { reason, error: reason };
|
|
841
|
+
}
|
|
842
|
+
let targetDecision;
|
|
753
843
|
try {
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
844
|
+
if (creatorRole !== undefined) {
|
|
845
|
+
targetDecision = options.targetPolicy.authorize(storedTarget, creatorRole);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
catch {
|
|
849
|
+
// A policy exception is settled as a refusal after the claim.
|
|
850
|
+
}
|
|
851
|
+
if (!targetDecision?.allowed) {
|
|
852
|
+
const reason = targetDecision?.reason ?? 'invalid-creator-role';
|
|
853
|
+
return { reason, error: reason };
|
|
854
|
+
}
|
|
855
|
+
const deepField = deepScheduleTargetField(storedTarget);
|
|
856
|
+
if (deepField !== undefined) {
|
|
857
|
+
return {
|
|
858
|
+
reason: 'input-too-deep',
|
|
859
|
+
error: runInputDepthMessage(deepField),
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
if (targetKind === 'agent') {
|
|
863
|
+
const agentTarget = normalizeAndSanitizeAgentTarget(scheduleId, storedTarget);
|
|
864
|
+
return agentTarget
|
|
865
|
+
? { target: agentTarget }
|
|
866
|
+
: { reason: 'invalid-agent-target', error: 'invalid agent target' };
|
|
867
|
+
}
|
|
868
|
+
const workflowTarget = normalizeAndSanitizeWorkflowTarget(storedTarget);
|
|
869
|
+
return workflowTarget
|
|
870
|
+
? { target: workflowTarget }
|
|
871
|
+
: { reason: 'invalid-workflow-target', error: 'invalid workflow target' };
|
|
872
|
+
};
|
|
873
|
+
const recordLostFire = async (result, scheduleId, target) => {
|
|
874
|
+
result.lost += 1;
|
|
875
|
+
await auditOrLog({ scheduleId, target, outcome: 'lost', reason: 'lost: concurrent-claim' }, undefined);
|
|
876
|
+
};
|
|
877
|
+
const skipAdmission = async (schedule, input, decision, advance, at, result, mutationEpoch, heldFireAt, jitterOffsetMs) => {
|
|
878
|
+
const event = { scheduleId: schedule.id, target: input.target.kind };
|
|
879
|
+
if (!store.skipScheduleFire) {
|
|
880
|
+
result.skipped += 1;
|
|
881
|
+
await auditOrLog({ ...event, outcome: 'skipped', reason: 'admission-unsupported' }, undefined);
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
const oneOff = schedule.at !== undefined;
|
|
885
|
+
const unavailable = decision === undefined;
|
|
886
|
+
const priorRefusals = advance.expectedNextFireAt === schedule.nextFireAt
|
|
887
|
+
? (schedule.admissionRefusals ?? 0)
|
|
888
|
+
: 0;
|
|
889
|
+
const pauseRequested = decision?.pause === true;
|
|
890
|
+
const requestedRetry = decision?.retryAt;
|
|
891
|
+
const wantsRetry = heldFireAt === undefined &&
|
|
892
|
+
!pauseRequested &&
|
|
893
|
+
requestedRetry !== undefined &&
|
|
894
|
+
requestedRetry > at &&
|
|
895
|
+
requestedRetry <= at + 86_400_000 &&
|
|
896
|
+
(oneOff ||
|
|
897
|
+
requestedRetry < (advance.nominalFireAt ?? advance.newNextFireAt));
|
|
898
|
+
const retryExhausted = wantsRetry && priorRefusals >= SCHEDULE_ADMISSION_MAX_RETRIES;
|
|
899
|
+
const retryAt = wantsRetry && !retryExhausted
|
|
900
|
+
? requestedRetry
|
|
901
|
+
: unavailable && oneOff
|
|
902
|
+
? at + 60_000
|
|
903
|
+
: undefined;
|
|
904
|
+
const complete = oneOff &&
|
|
905
|
+
!unavailable &&
|
|
906
|
+
retryAt === undefined &&
|
|
907
|
+
!pauseRequested &&
|
|
908
|
+
!retryExhausted;
|
|
909
|
+
const paused = pauseRequested || retryExhausted || complete;
|
|
910
|
+
const admissionRefusals = unavailable || retryExhausted
|
|
911
|
+
? priorRefusals
|
|
912
|
+
: wantsRetry
|
|
913
|
+
? priorRefusals + 1
|
|
914
|
+
: 0;
|
|
915
|
+
const reason = unavailable ? 'admission-unavailable' : 'admission-refused';
|
|
916
|
+
const admissionReason = decision?.reason ?? reason;
|
|
917
|
+
const scheduledFireAt = input.schedule.scheduledFireAt;
|
|
918
|
+
const skipped = await store.skipScheduleFire({
|
|
919
|
+
...(mutationEpoch === undefined ? {} : { mutationEpoch }),
|
|
920
|
+
scheduleId: schedule.id,
|
|
921
|
+
...advance,
|
|
922
|
+
...(heldFireAt === undefined ? {} : { expectedHeldFireAt: heldFireAt }),
|
|
923
|
+
...(retryAt !== undefined
|
|
924
|
+
? {
|
|
925
|
+
newNextFireAt: retryAt,
|
|
926
|
+
...(oneOff ? {} : { nominalFireAt: scheduledFireAt }),
|
|
927
|
+
}
|
|
928
|
+
: {}),
|
|
929
|
+
...(paused ? { status: 'paused' } : {}),
|
|
930
|
+
...(complete ? { completedAt: at } : {}),
|
|
931
|
+
admissionRefusals,
|
|
932
|
+
trigger: {
|
|
933
|
+
id: unavailable
|
|
934
|
+
? `scheduleAdmissionUnavailable:${schedule.id}:${scheduledFireAt}`
|
|
935
|
+
: input.dispatchId,
|
|
936
|
+
scheduleId: schedule.id,
|
|
937
|
+
runId: null,
|
|
938
|
+
scheduledFireAt,
|
|
939
|
+
actualFireAt: at,
|
|
940
|
+
outcome: 'skipped',
|
|
941
|
+
metadata: triggerMetadata({
|
|
942
|
+
reason,
|
|
943
|
+
admissionReason,
|
|
944
|
+
refusedAt: at,
|
|
945
|
+
...(retryAt === undefined ? {} : { retryAt }),
|
|
946
|
+
...(paused ? { paused: true } : {}),
|
|
947
|
+
...(retryExhausted ? { retryExhausted: true } : {}),
|
|
948
|
+
...(unavailable ? { unavailableAttempts: 1 } : {}),
|
|
949
|
+
...(heldFireAt === undefined ? {} : { heldFrom: heldFireAt }),
|
|
950
|
+
...(jitterOffsetMs === undefined ? {} : { jitterOffsetMs }),
|
|
951
|
+
scheduleOrigin: input.schedule,
|
|
952
|
+
}),
|
|
953
|
+
},
|
|
954
|
+
});
|
|
955
|
+
if (!skipped) {
|
|
956
|
+
await recordLostFire(result, event.scheduleId, event.target);
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
result.skipped += 1;
|
|
960
|
+
await auditOrLog({
|
|
961
|
+
...event,
|
|
962
|
+
outcome: 'skipped',
|
|
963
|
+
reason: unavailable ? reason : `${reason}:${admissionReason}`,
|
|
964
|
+
}, undefined);
|
|
965
|
+
};
|
|
966
|
+
const previousRunActive = async (scheduleId, deadline) => {
|
|
967
|
+
const trigger = await store.latestDispatchedTrigger?.(scheduleId);
|
|
968
|
+
if (performance.now() >= deadline)
|
|
969
|
+
return true;
|
|
970
|
+
if (trigger?.outcome === 'deferred')
|
|
971
|
+
return true;
|
|
972
|
+
const storedRef = trigger?.metadata?.dispatchRef;
|
|
973
|
+
if (storedRef === undefined)
|
|
974
|
+
return false;
|
|
975
|
+
const dispatch = storedDispatchRef(storedRef)?.ref;
|
|
976
|
+
if (!dispatch || dispatch.scheduleId !== scheduleId)
|
|
977
|
+
return true;
|
|
978
|
+
const threadlessAgentStart = dispatch.target === 'agent' && dispatch.mode === 'start';
|
|
979
|
+
let answer;
|
|
980
|
+
try {
|
|
981
|
+
answer = await options.status(dispatch);
|
|
982
|
+
}
|
|
983
|
+
catch (error) {
|
|
984
|
+
if (threadlessAgentStart && statusOf(error) === 404)
|
|
985
|
+
return false;
|
|
986
|
+
throw error;
|
|
987
|
+
}
|
|
988
|
+
if (answer === undefined)
|
|
989
|
+
return false;
|
|
990
|
+
const status = threadlessAgentStart
|
|
991
|
+
? (answer.summary?.status ?? answer.status)
|
|
992
|
+
: answer.status;
|
|
993
|
+
return !isTerminalRunStatus(status);
|
|
994
|
+
};
|
|
995
|
+
const fireOne = async (schedule, at, result, mutationEpoch, pass) => {
|
|
996
|
+
const storedTarget = schedule.target;
|
|
997
|
+
const targetType = auditTargetOfKind(storedTarget.type);
|
|
998
|
+
const oneOff = schedule.at !== undefined;
|
|
999
|
+
const heldOnly = !oneOff && schedule.heldFireAt !== undefined && schedule.nextFireAt > at;
|
|
1000
|
+
let plan;
|
|
1001
|
+
let nextEligibleFireAt;
|
|
1002
|
+
try {
|
|
1003
|
+
plan = planScheduleFire(heldOnly
|
|
1004
|
+
? { ...schedule, catchUp: undefined, jitterMs: undefined }
|
|
1005
|
+
: schedule, at);
|
|
1006
|
+
nextEligibleFireAt = plan.fire.nominal;
|
|
1007
|
+
if (plan.dropped && nextEligibleFireAt > at && schedule.jitterMs) {
|
|
1008
|
+
const [next] = previewScheduleFires(schedule, { after: at, count: 1 });
|
|
1009
|
+
nextEligibleFireAt = next?.fireAt ?? nextEligibleFireAt;
|
|
1010
|
+
}
|
|
760
1011
|
}
|
|
761
1012
|
catch {
|
|
1013
|
+
// A corrupt cron stays due until its timing is repaired.
|
|
762
1014
|
result.failed += 1;
|
|
763
1015
|
await auditOrLog({
|
|
764
1016
|
scheduleId: schedule.id,
|
|
@@ -768,6 +1020,225 @@ export function createScheduleTick(options) {
|
|
|
768
1020
|
}, undefined);
|
|
769
1021
|
return;
|
|
770
1022
|
}
|
|
1023
|
+
let creatorRole;
|
|
1024
|
+
try {
|
|
1025
|
+
creatorRole = scheduleCreatorRole(schedule);
|
|
1026
|
+
}
|
|
1027
|
+
catch {
|
|
1028
|
+
// Legacy rows without a creator role can be claimed for audit.
|
|
1029
|
+
}
|
|
1030
|
+
const preflight = targetPreflight(schedule.id, storedTarget, creatorRole);
|
|
1031
|
+
const policy = !oneOff &&
|
|
1032
|
+
'target' in preflight &&
|
|
1033
|
+
(preflight.target.type === 'workflow' ||
|
|
1034
|
+
preflight.target.threadId === undefined)
|
|
1035
|
+
? (schedule.overlapPolicy ?? defaultOverlapPolicy)
|
|
1036
|
+
: undefined;
|
|
1037
|
+
const checkOverlap = policy === 'skip' || policy === 'queue_one';
|
|
1038
|
+
const recordOverlapSkip = async (reason) => {
|
|
1039
|
+
result.skipped += 1;
|
|
1040
|
+
await auditOrLog({
|
|
1041
|
+
scheduleId: schedule.id,
|
|
1042
|
+
target: targetType,
|
|
1043
|
+
outcome: 'skipped',
|
|
1044
|
+
reason,
|
|
1045
|
+
}, undefined);
|
|
1046
|
+
};
|
|
1047
|
+
let previousActive = false;
|
|
1048
|
+
if (checkOverlap) {
|
|
1049
|
+
if (!store.latestDispatchedTrigger) {
|
|
1050
|
+
await recordOverlapSkip('overlap-unsupported');
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
const statusStartedAt = performance.now();
|
|
1054
|
+
if (statusStartedAt >= pass.deadline)
|
|
1055
|
+
return 'budget-spent';
|
|
1056
|
+
const statusDeadline = statusStartedAt + statusTimeoutMs;
|
|
1057
|
+
const deadline = Math.min(statusDeadline, pass.deadline);
|
|
1058
|
+
const active = await withDeadline(() => previousRunActive(schedule.id, deadline), deadline).catch(() => true);
|
|
1059
|
+
if (active === DEADLINE_EXPIRED && pass.deadline < statusDeadline) {
|
|
1060
|
+
return 'budget-spent';
|
|
1061
|
+
}
|
|
1062
|
+
previousActive = active !== false;
|
|
1063
|
+
if (previousActive && schedule.nextFireAt > at)
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
// Claiming a hold leaves the newer due time armed for the next overlap check.
|
|
1067
|
+
const heldFireAt = !oneOff && !previousActive ? schedule.heldFireAt : undefined;
|
|
1068
|
+
if (heldFireAt === undefined && plan.catchUpEnumerationCapped) {
|
|
1069
|
+
console.warn(JSON.stringify({
|
|
1070
|
+
type: 'schedule-catch-up-enumeration-capped',
|
|
1071
|
+
scheduleId: schedule.id,
|
|
1072
|
+
}));
|
|
1073
|
+
}
|
|
1074
|
+
const owner = await options.ownership?.owner('schedule', schedule.id);
|
|
1075
|
+
const scheduleOrigin = {
|
|
1076
|
+
id: schedule.id,
|
|
1077
|
+
...(owner === undefined
|
|
1078
|
+
? {}
|
|
1079
|
+
: { owner: { id: owner.id, kind: owner.kind } }),
|
|
1080
|
+
...(creatorRole === undefined ? {} : { creatorRole }),
|
|
1081
|
+
...(schedule.ownerType === undefined
|
|
1082
|
+
? {}
|
|
1083
|
+
: { ownerType: schedule.ownerType }),
|
|
1084
|
+
...(schedule.ownerId === undefined ? {} : { ownerId: schedule.ownerId }),
|
|
1085
|
+
...(schedule.metadata === undefined
|
|
1086
|
+
? {}
|
|
1087
|
+
: { metadata: structuredClone(schedule.metadata) }),
|
|
1088
|
+
scheduledFireAt: heldFireAt ?? plan.fire.nominal,
|
|
1089
|
+
timing: oneOff ? 'at' : 'cron',
|
|
1090
|
+
};
|
|
1091
|
+
const { successor } = plan;
|
|
1092
|
+
const dropped = heldFireAt === undefined ? plan.dropped : undefined;
|
|
1093
|
+
if (dropped) {
|
|
1094
|
+
if (performance.now() >= pass.deadline)
|
|
1095
|
+
return 'budget-spent';
|
|
1096
|
+
const event = { scheduleId: schedule.id, target: targetType };
|
|
1097
|
+
if (!store.skipScheduleFire) {
|
|
1098
|
+
result.skipped += 1;
|
|
1099
|
+
await auditOrLog({ ...event, outcome: 'skipped', reason: 'catch-up-unsupported' }, undefined);
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
1102
|
+
const reason = 'catch-up-exceeded';
|
|
1103
|
+
const skipped = await store.skipScheduleFire({
|
|
1104
|
+
...(mutationEpoch === undefined ? {} : { mutationEpoch }),
|
|
1105
|
+
scheduleId: schedule.id,
|
|
1106
|
+
expectedNextFireAt: schedule.nextFireAt,
|
|
1107
|
+
newNextFireAt: nextEligibleFireAt,
|
|
1108
|
+
nominalFireAt: plan.fire.nominal,
|
|
1109
|
+
admissionRefusals: 0,
|
|
1110
|
+
trigger: {
|
|
1111
|
+
id: mintPathSafeId('scheduleTrigger'),
|
|
1112
|
+
scheduleId: schedule.id,
|
|
1113
|
+
runId: null,
|
|
1114
|
+
scheduledFireAt: dropped.first,
|
|
1115
|
+
actualFireAt: at,
|
|
1116
|
+
outcome: 'skipped',
|
|
1117
|
+
metadata: triggerMetadata({
|
|
1118
|
+
reason,
|
|
1119
|
+
skippedCount: dropped.count,
|
|
1120
|
+
firstScheduledFireAt: dropped.first,
|
|
1121
|
+
lastScheduledFireAt: dropped.last,
|
|
1122
|
+
scheduleOrigin: {
|
|
1123
|
+
...scheduleOrigin,
|
|
1124
|
+
scheduledFireAt: dropped.first,
|
|
1125
|
+
},
|
|
1126
|
+
}),
|
|
1127
|
+
},
|
|
1128
|
+
});
|
|
1129
|
+
if (!skipped) {
|
|
1130
|
+
await recordLostFire(result, schedule.id, targetType);
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
result.skipped += 1;
|
|
1134
|
+
await auditOrLog({ ...event, outcome: 'skipped', reason }, undefined);
|
|
1135
|
+
if (nextEligibleFireAt > at)
|
|
1136
|
+
return;
|
|
1137
|
+
}
|
|
1138
|
+
const advance = {
|
|
1139
|
+
expectedNextFireAt: dropped ? nextEligibleFireAt : schedule.nextFireAt,
|
|
1140
|
+
newNextFireAt: heldFireAt === undefined
|
|
1141
|
+
? (successor?.fireAt ?? plan.fire.nominal)
|
|
1142
|
+
: schedule.nextFireAt,
|
|
1143
|
+
...(heldFireAt === undefined && successor !== undefined
|
|
1144
|
+
? { nominalFireAt: successor.nominal }
|
|
1145
|
+
: {}),
|
|
1146
|
+
};
|
|
1147
|
+
// A hook-chosen retry replaces the due time with its own delay.
|
|
1148
|
+
const armedJitter = schedule.nominalFireAt === plan.fire.nominal
|
|
1149
|
+
? Math.max(0, schedule.nextFireAt - plan.fire.nominal)
|
|
1150
|
+
: 0;
|
|
1151
|
+
const jitterOffsetMs = !oneOff &&
|
|
1152
|
+
heldFireAt === undefined &&
|
|
1153
|
+
!schedule.admissionRefusals &&
|
|
1154
|
+
(armedJitter > 0 || schedule.jitterMs !== undefined)
|
|
1155
|
+
? armedJitter
|
|
1156
|
+
: undefined;
|
|
1157
|
+
const fireMetadata = (extra) => triggerMetadata({
|
|
1158
|
+
...extra,
|
|
1159
|
+
...(heldFireAt === undefined ? {} : { heldFrom: heldFireAt }),
|
|
1160
|
+
...(jitterOffsetMs === undefined ? {} : { jitterOffsetMs }),
|
|
1161
|
+
scheduleOrigin,
|
|
1162
|
+
});
|
|
1163
|
+
const dispatchId = mintPathSafeId('scheduleTrigger');
|
|
1164
|
+
if (previousActive) {
|
|
1165
|
+
const overlapAdvance = {
|
|
1166
|
+
...(mutationEpoch === undefined ? {} : { mutationEpoch }),
|
|
1167
|
+
scheduleId: schedule.id,
|
|
1168
|
+
...advance,
|
|
1169
|
+
};
|
|
1170
|
+
if (policy === 'queue_one' && schedule.heldFireAt === undefined) {
|
|
1171
|
+
if (!store.holdScheduleFire || !store.listHeldSchedules) {
|
|
1172
|
+
await recordOverlapSkip('overlap-unsupported');
|
|
1173
|
+
}
|
|
1174
|
+
else {
|
|
1175
|
+
const held = await store.holdScheduleFire({
|
|
1176
|
+
...overlapAdvance,
|
|
1177
|
+
heldFireAt: scheduleOrigin.scheduledFireAt,
|
|
1178
|
+
});
|
|
1179
|
+
if (!held)
|
|
1180
|
+
await recordLostFire(result, schedule.id, targetType);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
else if (!store.skipScheduleFire) {
|
|
1184
|
+
await recordOverlapSkip('overlap-unsupported');
|
|
1185
|
+
}
|
|
1186
|
+
else {
|
|
1187
|
+
const skipped = await store.skipScheduleFire({
|
|
1188
|
+
...overlapAdvance,
|
|
1189
|
+
admissionRefusals: 0,
|
|
1190
|
+
trigger: {
|
|
1191
|
+
id: dispatchId,
|
|
1192
|
+
scheduleId: schedule.id,
|
|
1193
|
+
runId: null,
|
|
1194
|
+
scheduledFireAt: scheduleOrigin.scheduledFireAt,
|
|
1195
|
+
actualFireAt: at,
|
|
1196
|
+
outcome: 'skipped',
|
|
1197
|
+
metadata: fireMetadata({ reason: 'overlap' }),
|
|
1198
|
+
},
|
|
1199
|
+
});
|
|
1200
|
+
if (skipped)
|
|
1201
|
+
await recordOverlapSkip('overlap');
|
|
1202
|
+
else
|
|
1203
|
+
await recordLostFire(result, schedule.id, targetType);
|
|
1204
|
+
}
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1207
|
+
if ('target' in preflight && admit) {
|
|
1208
|
+
const input = {
|
|
1209
|
+
schedule: scheduleOrigin,
|
|
1210
|
+
target: scheduleAdmissionTarget(preflight.target),
|
|
1211
|
+
dispatchId,
|
|
1212
|
+
...(options.deploymentTag === undefined
|
|
1213
|
+
? {}
|
|
1214
|
+
: { deploymentTag: options.deploymentTag }),
|
|
1215
|
+
};
|
|
1216
|
+
const admissionStartedAt = performance.now();
|
|
1217
|
+
if (admissionStartedAt >= pass.deadline)
|
|
1218
|
+
return 'budget-spent';
|
|
1219
|
+
let decision;
|
|
1220
|
+
if (!pass.admissionTimedOut) {
|
|
1221
|
+
const hookDeadline = admissionStartedAt + admitTimeoutMs;
|
|
1222
|
+
try {
|
|
1223
|
+
const answer = await withDeadline(() => admit(structuredClone(input)), Math.min(hookDeadline, pass.deadline));
|
|
1224
|
+
if (answer === DEADLINE_EXPIRED) {
|
|
1225
|
+
if (pass.deadline < hookDeadline)
|
|
1226
|
+
return 'budget-spent';
|
|
1227
|
+
pass.admissionTimedOut = true;
|
|
1228
|
+
}
|
|
1229
|
+
else {
|
|
1230
|
+
decision = normalizeAdmission(answer);
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
catch {
|
|
1234
|
+
// A broken hook cannot authorize the fire.
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
if (!decision?.admit) {
|
|
1238
|
+
await skipAdmission(schedule, input, decision, advance, at, result, mutationEpoch, heldFireAt, jitterOffsetMs);
|
|
1239
|
+
return;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
771
1242
|
// 2. Mint the provisional runId before the CAS so lastRunId identifies this
|
|
772
1243
|
// claim even when a cap later consumes it without dispatch.
|
|
773
1244
|
const runId = mintPathSafeId('scheduleTick');
|
|
@@ -781,29 +1252,63 @@ export function createScheduleTick(options) {
|
|
|
781
1252
|
// null for a skip); `lastRunId` is a best-effort last-claim marker, not a
|
|
782
1253
|
// guarantee the run was dispatched.
|
|
783
1254
|
const claimTrigger = {
|
|
784
|
-
id:
|
|
1255
|
+
id: dispatchId,
|
|
785
1256
|
scheduleId: schedule.id,
|
|
786
1257
|
runId,
|
|
787
|
-
scheduledFireAt:
|
|
1258
|
+
scheduledFireAt: scheduleOrigin.scheduledFireAt,
|
|
788
1259
|
actualFireAt: at,
|
|
789
1260
|
outcome: 'deferred',
|
|
790
1261
|
error: 'dispatch has not reached an authoritative target state',
|
|
791
|
-
metadata:
|
|
1262
|
+
metadata: fireMetadata({
|
|
792
1263
|
...(mutationEpoch === undefined ? {} : { mutationEpoch }),
|
|
793
1264
|
reason: 'dispatch-preparing',
|
|
794
1265
|
reconcileAttempts: 0,
|
|
795
1266
|
reconcileAfter: at,
|
|
796
1267
|
}),
|
|
797
1268
|
};
|
|
798
|
-
const
|
|
799
|
-
...(mutationEpoch === undefined ? {} : { mutationEpoch }),
|
|
1269
|
+
const settleClaimFailure = (reason, error) => settleTrigger(result, () => store.failDeferredTrigger(claimTrigger.id, schedule.id, error instanceof Error ? error.message : String(error), fireMetadata({ reason })), 'failed', {
|
|
800
1270
|
scheduleId: schedule.id,
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
1271
|
+
target: targetType,
|
|
1272
|
+
outcome: 'failed',
|
|
1273
|
+
reason,
|
|
1274
|
+
}, runId);
|
|
1275
|
+
let claimed;
|
|
1276
|
+
try {
|
|
1277
|
+
claimed = await store.claimScheduleFire({
|
|
1278
|
+
...(mutationEpoch === undefined ? {} : { mutationEpoch }),
|
|
1279
|
+
scheduleId: schedule.id,
|
|
1280
|
+
...advance,
|
|
1281
|
+
expectedNextFireAt: heldFireAt ?? advance.expectedNextFireAt,
|
|
1282
|
+
...(checkOverlap
|
|
1283
|
+
? { expectedLastRunId: schedule.lastRunId ?? null }
|
|
1284
|
+
: {}),
|
|
1285
|
+
...(oneOff ? { complete: true } : {}),
|
|
1286
|
+
...(heldFireAt === undefined ? {} : { held: true }),
|
|
1287
|
+
actualFireAt: at,
|
|
1288
|
+
runId,
|
|
1289
|
+
trigger: claimTrigger,
|
|
1290
|
+
});
|
|
1291
|
+
}
|
|
1292
|
+
catch (error) {
|
|
1293
|
+
let storedClaim;
|
|
1294
|
+
try {
|
|
1295
|
+
storedClaim = store.getTrigger
|
|
1296
|
+
? await store.getTrigger(schedule.id, claimTrigger.id)
|
|
1297
|
+
: (await store.listDeferredTriggers()).find((trigger) => trigger.scheduleId === schedule.id &&
|
|
1298
|
+
trigger.id === claimTrigger.id);
|
|
1299
|
+
}
|
|
1300
|
+
catch (readError) {
|
|
1301
|
+
result.deferred += 1;
|
|
1302
|
+
logBookkeepingError(schedule.id, runId, readError);
|
|
1303
|
+
return;
|
|
1304
|
+
}
|
|
1305
|
+
if (!storedClaim)
|
|
1306
|
+
throw error;
|
|
1307
|
+
if (storedClaim.outcome === 'deferred') {
|
|
1308
|
+
await settleClaimFailure('post-claim-error', error);
|
|
1309
|
+
}
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
807
1312
|
if (!claimed) {
|
|
808
1313
|
result.lost += 1;
|
|
809
1314
|
try {
|
|
@@ -825,81 +1330,127 @@ export function createScheduleTick(options) {
|
|
|
825
1330
|
}
|
|
826
1331
|
return;
|
|
827
1332
|
}
|
|
828
|
-
const recordUndispatched = (
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
1333
|
+
const recordUndispatched = async (outcome, reason, error) => {
|
|
1334
|
+
await store.recordTrigger({
|
|
1335
|
+
...claimTrigger,
|
|
1336
|
+
runId: null,
|
|
1337
|
+
outcome,
|
|
1338
|
+
error,
|
|
1339
|
+
metadata: fireMetadata({ reason }),
|
|
1340
|
+
});
|
|
1341
|
+
result[outcome] += 1;
|
|
1342
|
+
await auditOrLog({ scheduleId: schedule.id, target: targetType, outcome, reason }, runId);
|
|
1343
|
+
};
|
|
1344
|
+
const recordPublished = (auditTarget, dispatchedRunId, dispatchRef) => settleTrigger(result, () => store.recordTrigger({
|
|
836
1345
|
...claimTrigger,
|
|
837
1346
|
runId: dispatchedRunId,
|
|
838
1347
|
outcome: 'published',
|
|
839
1348
|
error: undefined,
|
|
840
|
-
metadata:
|
|
1349
|
+
metadata: fireMetadata({ dispatchRef }),
|
|
841
1350
|
}), 'fired', {
|
|
842
1351
|
scheduleId: schedule.id,
|
|
843
1352
|
target: auditTarget,
|
|
844
1353
|
outcome: 'published',
|
|
845
1354
|
runId: dispatchedRunId,
|
|
846
1355
|
}, dispatchedRunId);
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
return;
|
|
853
|
-
}
|
|
854
|
-
let targetDecision;
|
|
855
|
-
try {
|
|
856
|
-
targetDecision = options.targetPolicy.authorize(storedTarget, scheduleCreatorRole(schedule));
|
|
857
|
-
}
|
|
858
|
-
catch {
|
|
859
|
-
// A legacy/corrupt row with no creator role is never dispatched.
|
|
860
|
-
}
|
|
861
|
-
if (!targetDecision?.allowed) {
|
|
862
|
-
const reason = targetDecision?.reason ?? 'invalid-creator-role';
|
|
863
|
-
await recordUndispatched(targetType, 'failed', reason, reason);
|
|
864
|
-
return;
|
|
865
|
-
}
|
|
866
|
-
const deepField = deepScheduleTargetField(storedTarget);
|
|
867
|
-
if (deepField !== undefined) {
|
|
868
|
-
await recordUndispatched(targetType, 'failed', 'input-too-deep', runInputDepthMessage(deepField));
|
|
869
|
-
return;
|
|
870
|
-
}
|
|
871
|
-
if (targetKind === 'agent') {
|
|
872
|
-
const target = normalizeAndSanitizeAgentTarget(schedule.id, storedTarget);
|
|
873
|
-
if (!target) {
|
|
874
|
-
await recordUndispatched('agent', 'failed', 'invalid-agent-target', 'invalid agent target');
|
|
875
|
-
return;
|
|
876
|
-
}
|
|
877
|
-
const firedRunId = runId;
|
|
878
|
-
const threaded = target.threadId !== undefined;
|
|
879
|
-
const topologyThreadId = target.threadId ?? mintPathSafeId('scheduleThread');
|
|
880
|
-
const providerOptions = agentScheduleProviderOptions(schedule.id, target);
|
|
881
|
-
if (threaded) {
|
|
882
|
-
if (!options.signalAgent) {
|
|
883
|
-
await recordUndispatched('agent', 'skipped', 'agent-target-unsupported');
|
|
1356
|
+
const buildClaimedDispatch = async () => {
|
|
1357
|
+
let failureReason = 'post-claim-error';
|
|
1358
|
+
try {
|
|
1359
|
+
if ('reason' in preflight) {
|
|
1360
|
+
await recordUndispatched('failed', preflight.reason, preflight.error);
|
|
884
1361
|
return;
|
|
885
1362
|
}
|
|
886
|
-
const
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
1363
|
+
const { target } = preflight;
|
|
1364
|
+
const consultRunCap = async () => {
|
|
1365
|
+
if (!options.runCap)
|
|
1366
|
+
return true;
|
|
1367
|
+
const input = {
|
|
1368
|
+
schedule: structuredClone(scheduleOrigin),
|
|
1369
|
+
target: scheduleAdmissionTarget(target),
|
|
1370
|
+
dispatchId,
|
|
1371
|
+
};
|
|
1372
|
+
failureReason = 'run-cap-error';
|
|
1373
|
+
const allowed = await options.runCap(input);
|
|
1374
|
+
failureReason = 'post-claim-error';
|
|
1375
|
+
return allowed;
|
|
895
1376
|
};
|
|
896
|
-
|
|
1377
|
+
const identifiers = { scheduleId: schedule.id, dispatchId, runId };
|
|
1378
|
+
if (target.type === 'agent') {
|
|
1379
|
+
const threaded = target.threadId !== undefined;
|
|
1380
|
+
const threadId = target.threadId ?? mintPathSafeId('scheduleThread');
|
|
1381
|
+
const providerOptions = agentScheduleProviderOptions(schedule.id, target);
|
|
1382
|
+
const agent = {
|
|
1383
|
+
...identifiers,
|
|
1384
|
+
target: 'agent',
|
|
1385
|
+
agentId: target.agentId,
|
|
1386
|
+
threadId,
|
|
1387
|
+
agentTarget: target,
|
|
1388
|
+
};
|
|
1389
|
+
if (threaded) {
|
|
1390
|
+
const signalAgent = options.signalAgent;
|
|
1391
|
+
if (!signalAgent) {
|
|
1392
|
+
await recordUndispatched('skipped', 'agent-target-unsupported');
|
|
1393
|
+
return;
|
|
1394
|
+
}
|
|
1395
|
+
return {
|
|
1396
|
+
dispatch: {
|
|
1397
|
+
...agent,
|
|
1398
|
+
mode: 'signal',
|
|
1399
|
+
},
|
|
1400
|
+
providerOptions,
|
|
1401
|
+
signalAgent,
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
const startAgent = options.startAgent;
|
|
1405
|
+
if (!startAgent) {
|
|
1406
|
+
await recordUndispatched('skipped', 'agent-target-unsupported');
|
|
1407
|
+
return;
|
|
1408
|
+
}
|
|
1409
|
+
if (!(await consultRunCap())) {
|
|
1410
|
+
await recordUndispatched('skipped', 'run-capped');
|
|
1411
|
+
return;
|
|
1412
|
+
}
|
|
1413
|
+
return {
|
|
1414
|
+
dispatch: {
|
|
1415
|
+
...agent,
|
|
1416
|
+
mode: 'start',
|
|
1417
|
+
},
|
|
1418
|
+
providerOptions,
|
|
1419
|
+
startAgent,
|
|
1420
|
+
};
|
|
1421
|
+
}
|
|
1422
|
+
if (!(await consultRunCap())) {
|
|
1423
|
+
await recordUndispatched('skipped', 'run-capped');
|
|
897
1424
|
return;
|
|
1425
|
+
}
|
|
1426
|
+
return {
|
|
1427
|
+
dispatch: {
|
|
1428
|
+
...identifiers,
|
|
1429
|
+
target: 'workflow',
|
|
1430
|
+
workflowId: target.workflowId,
|
|
1431
|
+
workflowTarget: target,
|
|
1432
|
+
},
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
catch (error) {
|
|
1436
|
+
await settleClaimFailure(failureReason, error);
|
|
1437
|
+
}
|
|
1438
|
+
};
|
|
1439
|
+
const pending = await buildClaimedDispatch();
|
|
1440
|
+
if (!pending)
|
|
1441
|
+
return;
|
|
1442
|
+
if (!(await prepareDispatch(pending.dispatch, claimTrigger, result)))
|
|
1443
|
+
return;
|
|
1444
|
+
if (pending.providerOptions !== undefined) {
|
|
1445
|
+
const { dispatch, providerOptions } = pending;
|
|
1446
|
+
const { agentTarget: target, threadId: topologyThreadId, runId: firedRunId, } = dispatch;
|
|
1447
|
+
if (pending.signalAgent) {
|
|
898
1448
|
let receipt;
|
|
899
1449
|
try {
|
|
900
|
-
receipt = await
|
|
1450
|
+
receipt = await pending.signalAgent.call(options, {
|
|
901
1451
|
...(mutationEpoch === undefined ? {} : { mutationEpoch }),
|
|
902
1452
|
scheduleId: schedule.id,
|
|
1453
|
+
schedule: scheduleOrigin,
|
|
903
1454
|
target,
|
|
904
1455
|
...(options.deploymentTag !== undefined
|
|
905
1456
|
? { deploymentTag: options.deploymentTag }
|
|
@@ -930,7 +1481,7 @@ export function createScheduleTick(options) {
|
|
|
930
1481
|
runId: receipt.runId ?? null,
|
|
931
1482
|
outcome: receipt.outcome,
|
|
932
1483
|
error: undefined,
|
|
933
|
-
metadata:
|
|
1484
|
+
metadata: fireMetadata({
|
|
934
1485
|
action: receipt.action,
|
|
935
1486
|
...(receipt.signalId !== undefined
|
|
936
1487
|
? { signalId: receipt.signalId }
|
|
@@ -944,32 +1495,12 @@ export function createScheduleTick(options) {
|
|
|
944
1495
|
}, receipt.runId ?? firedRunId);
|
|
945
1496
|
return;
|
|
946
1497
|
}
|
|
947
|
-
if (!options.startAgent) {
|
|
948
|
-
await recordUndispatched('agent', 'skipped', 'agent-target-unsupported');
|
|
949
|
-
return;
|
|
950
|
-
}
|
|
951
|
-
const allowed = options.runCap ? await options.runCap() : true;
|
|
952
|
-
if (!allowed) {
|
|
953
|
-
await recordUndispatched('agent', 'skipped', 'run-capped');
|
|
954
|
-
return;
|
|
955
|
-
}
|
|
956
|
-
const dispatch = {
|
|
957
|
-
scheduleId: schedule.id,
|
|
958
|
-
dispatchId: claimTrigger.id,
|
|
959
|
-
target: 'agent',
|
|
960
|
-
agentId: target.agentId,
|
|
961
|
-
threadId: topologyThreadId,
|
|
962
|
-
runId: firedRunId,
|
|
963
|
-
mode: 'start',
|
|
964
|
-
agentTarget: target,
|
|
965
|
-
};
|
|
966
|
-
if (!(await prepareDispatch(dispatch, claimTrigger, result)))
|
|
967
|
-
return;
|
|
968
1498
|
let summary;
|
|
969
1499
|
try {
|
|
970
|
-
summary = await
|
|
1500
|
+
summary = await pending.startAgent.call(options, {
|
|
971
1501
|
...(mutationEpoch === undefined ? {} : { mutationEpoch }),
|
|
972
1502
|
scheduleId: schedule.id,
|
|
1503
|
+
schedule: scheduleOrigin,
|
|
973
1504
|
dispatchId: claimTrigger.id,
|
|
974
1505
|
target,
|
|
975
1506
|
...(options.deploymentTag !== undefined
|
|
@@ -977,7 +1508,7 @@ export function createScheduleTick(options) {
|
|
|
977
1508
|
: {}),
|
|
978
1509
|
runId: firedRunId,
|
|
979
1510
|
topologyThreadId,
|
|
980
|
-
threaded,
|
|
1511
|
+
threaded: false,
|
|
981
1512
|
entryPath: 'schedule.fire',
|
|
982
1513
|
requestContext: target.requestContext ?? {},
|
|
983
1514
|
streamRequestContext: target.ifIdle?.streamOptions?.requestContext ?? {},
|
|
@@ -995,33 +1526,11 @@ export function createScheduleTick(options) {
|
|
|
995
1526
|
}, error, result);
|
|
996
1527
|
return;
|
|
997
1528
|
}
|
|
998
|
-
await recordPublished('agent', summary.runId ?? firedRunId);
|
|
1529
|
+
await recordPublished('agent', summary.runId ?? firedRunId, dispatch);
|
|
999
1530
|
return;
|
|
1000
1531
|
}
|
|
1001
|
-
const
|
|
1002
|
-
|
|
1003
|
-
await recordUndispatched('workflow', 'failed', 'invalid-workflow-target', 'invalid workflow target');
|
|
1004
|
-
return;
|
|
1005
|
-
}
|
|
1006
|
-
// 5. Workflow target: consult the run cap.
|
|
1007
|
-
const allowed = options.runCap ? await options.runCap() : true;
|
|
1008
|
-
if (!allowed) {
|
|
1009
|
-
// Capped: the schedule stays healthy (already advanced) and is audited.
|
|
1010
|
-
await recordUndispatched('workflow', 'skipped', 'run-capped');
|
|
1011
|
-
return;
|
|
1012
|
-
}
|
|
1013
|
-
// 7. Fire the workflow run (runId is defined by construction here).
|
|
1014
|
-
const firedRunId = runId;
|
|
1015
|
-
const dispatch = {
|
|
1016
|
-
scheduleId: schedule.id,
|
|
1017
|
-
dispatchId: claimTrigger.id,
|
|
1018
|
-
target: 'workflow',
|
|
1019
|
-
workflowId: target.workflowId,
|
|
1020
|
-
runId: firedRunId,
|
|
1021
|
-
workflowTarget: target,
|
|
1022
|
-
};
|
|
1023
|
-
if (!(await prepareDispatch(dispatch, claimTrigger, result)))
|
|
1024
|
-
return;
|
|
1532
|
+
const { dispatch: workflowDispatch } = pending;
|
|
1533
|
+
const { workflowTarget } = workflowDispatch;
|
|
1025
1534
|
// The try wraps ONLY the start() dispatch. A post-dispatch bookkeeping
|
|
1026
1535
|
// failure (a transient recordTrigger/audit throw) must NOT be reclassified as
|
|
1027
1536
|
// a start failure — that would double-count and audit a run that actually ran
|
|
@@ -1031,21 +1540,22 @@ export function createScheduleTick(options) {
|
|
|
1031
1540
|
summary = await start({
|
|
1032
1541
|
...(mutationEpoch === undefined ? {} : { mutationEpoch }),
|
|
1033
1542
|
scheduleId: schedule.id,
|
|
1543
|
+
schedule: scheduleOrigin,
|
|
1034
1544
|
dispatchId: claimTrigger.id,
|
|
1035
|
-
workflowId:
|
|
1036
|
-
runId
|
|
1037
|
-
inputData:
|
|
1038
|
-
initialState:
|
|
1039
|
-
requestContext:
|
|
1545
|
+
workflowId: workflowTarget.workflowId,
|
|
1546
|
+
runId,
|
|
1547
|
+
inputData: workflowTarget.inputData,
|
|
1548
|
+
initialState: workflowTarget.initialState,
|
|
1549
|
+
requestContext: workflowTarget.requestContext ?? {},
|
|
1040
1550
|
});
|
|
1041
1551
|
}
|
|
1042
1552
|
catch (error) {
|
|
1043
|
-
await reconcileStartError(
|
|
1553
|
+
await reconcileStartError(workflowDispatch, {
|
|
1044
1554
|
...claimTrigger,
|
|
1045
1555
|
error: error instanceof Error ? error.message : String(error),
|
|
1046
1556
|
metadata: triggerMetadata({
|
|
1047
1557
|
...(claimTrigger.metadata ?? {}),
|
|
1048
|
-
dispatchRef:
|
|
1558
|
+
dispatchRef: workflowDispatch,
|
|
1049
1559
|
}),
|
|
1050
1560
|
}, error, result);
|
|
1051
1561
|
return;
|
|
@@ -1053,7 +1563,7 @@ export function createScheduleTick(options) {
|
|
|
1053
1563
|
// The run WAS dispatched. Record it as `published` (write-once at dispatch,
|
|
1054
1564
|
// per core's ScheduleTriggerOutcome doc). Bookkeeping failures are logged
|
|
1055
1565
|
// locally and do not reclassify the successful dispatch as a start failure.
|
|
1056
|
-
await recordPublished('workflow', summary.runId ??
|
|
1566
|
+
await recordPublished('workflow', summary.runId ?? runId, workflowDispatch);
|
|
1057
1567
|
};
|
|
1058
1568
|
const idlePass = () => ({
|
|
1059
1569
|
due: 0,
|
|
@@ -1095,7 +1605,16 @@ export function createScheduleTick(options) {
|
|
|
1095
1605
|
if (!admitted)
|
|
1096
1606
|
return idlePass();
|
|
1097
1607
|
const at = now();
|
|
1098
|
-
const due = await store.listDueSchedules(at, limit);
|
|
1608
|
+
const due = [...(await store.listDueSchedules(at, limit))];
|
|
1609
|
+
const heldSlots = limit - due.length;
|
|
1610
|
+
if (heldSlots > 0 && store.listHeldSchedules) {
|
|
1611
|
+
const dueIds = new Set(due.map(({ id }) => id));
|
|
1612
|
+
const held = await store.listHeldSchedules(at, heldSlots);
|
|
1613
|
+
for (const schedule of held) {
|
|
1614
|
+
if (!dueIds.has(schedule.id))
|
|
1615
|
+
due.push(schedule);
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1099
1618
|
const result = {
|
|
1100
1619
|
due: due.length,
|
|
1101
1620
|
fired: 0,
|
|
@@ -1106,8 +1625,8 @@ export function createScheduleTick(options) {
|
|
|
1106
1625
|
lost: 0,
|
|
1107
1626
|
};
|
|
1108
1627
|
// Reconciliation and the due fires are independent: a failed deferred
|
|
1109
|
-
// listing
|
|
1110
|
-
// the maintenance
|
|
1628
|
+
// listing can fail while there is still time to process due fires. The
|
|
1629
|
+
// pass rethrows that failure after the due loop so maintenance reports it.
|
|
1111
1630
|
let reconcileFailure;
|
|
1112
1631
|
try {
|
|
1113
1632
|
await reconcileDeferred(result);
|
|
@@ -1115,11 +1634,19 @@ export function createScheduleTick(options) {
|
|
|
1115
1634
|
catch (error) {
|
|
1116
1635
|
reconcileFailure = { error };
|
|
1117
1636
|
}
|
|
1118
|
-
|
|
1637
|
+
const pass = {
|
|
1638
|
+
deadline: admit ? performance.now() + passBudgetMs : Infinity,
|
|
1639
|
+
admissionTimedOut: false,
|
|
1640
|
+
};
|
|
1641
|
+
for (const [index, schedule] of due.entries()) {
|
|
1119
1642
|
// Per-schedule isolation: one wedged row (an unexpected store/audit throw)
|
|
1120
1643
|
// must not abort the pass and strand every due schedule behind it.
|
|
1121
1644
|
try {
|
|
1122
|
-
|
|
1645
|
+
if (performance.now() < pass.deadline &&
|
|
1646
|
+
(await fireOne(schedule, at, result, mutationEpoch, pass)) !==
|
|
1647
|
+
'budget-spent') {
|
|
1648
|
+
continue;
|
|
1649
|
+
}
|
|
1123
1650
|
}
|
|
1124
1651
|
catch (error) {
|
|
1125
1652
|
result.failed += 1;
|
|
@@ -1128,7 +1655,13 @@ export function createScheduleTick(options) {
|
|
|
1128
1655
|
scheduleId: schedule.id,
|
|
1129
1656
|
error: error instanceof Error ? error.message : String(error),
|
|
1130
1657
|
}));
|
|
1658
|
+
continue;
|
|
1131
1659
|
}
|
|
1660
|
+
console.warn(JSON.stringify({
|
|
1661
|
+
type: 'schedule-tick-pass-budget-spent',
|
|
1662
|
+
remaining: due.length - index,
|
|
1663
|
+
}));
|
|
1664
|
+
break;
|
|
1132
1665
|
}
|
|
1133
1666
|
if (reconcileFailure)
|
|
1134
1667
|
throw reconcileFailure.error;
|