@nagi-js/core 0.1.1-rc.15 → 0.1.1-rc.17
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/dist/index.d.ts +45 -2
- package/dist/index.js +227 -12
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -36,7 +36,7 @@ type RunDescription = {
|
|
|
36
36
|
|
|
37
37
|
type ReaperDecision = {
|
|
38
38
|
readonly tag: "skip";
|
|
39
|
-
readonly reason: "terminal" | "still-live";
|
|
39
|
+
readonly reason: "terminal" | "still-live" | "child-active";
|
|
40
40
|
} | {
|
|
41
41
|
readonly tag: "reap";
|
|
42
42
|
readonly nextAttempt: AttemptNumber;
|
|
@@ -50,6 +50,7 @@ declare function decideExpiredLeaseAction(args: {
|
|
|
50
50
|
readonly expiresAt: Date;
|
|
51
51
|
};
|
|
52
52
|
readonly stepStatus: StepRunStatus;
|
|
53
|
+
readonly childActive: boolean;
|
|
53
54
|
readonly now: Date;
|
|
54
55
|
}): ReaperDecision;
|
|
55
56
|
interface ReapedLease {
|
|
@@ -481,6 +482,7 @@ interface WorkerConfig {
|
|
|
481
482
|
readonly concurrency?: number;
|
|
482
483
|
readonly pollIntervalMs?: Millis;
|
|
483
484
|
readonly signal?: AbortSignal;
|
|
485
|
+
readonly timerSweepIntervalMs?: Millis;
|
|
484
486
|
}
|
|
485
487
|
interface WorkerRunOnceOpts {
|
|
486
488
|
readonly maxSteps?: number;
|
|
@@ -515,6 +517,12 @@ type SettleSignalResult = {
|
|
|
515
517
|
} | {
|
|
516
518
|
readonly tag: "noop";
|
|
517
519
|
};
|
|
520
|
+
interface TimedOutSignal {
|
|
521
|
+
readonly runId: RunId$1;
|
|
522
|
+
readonly stepId: StepId;
|
|
523
|
+
readonly attempt: AttemptNumber;
|
|
524
|
+
readonly fireAt: Date;
|
|
525
|
+
}
|
|
518
526
|
interface Store {
|
|
519
527
|
appendFact(runId: RunId$1, fact: Fact): Promise<void>;
|
|
520
528
|
loadRunState(runId: RunId$1): Promise<RunState>;
|
|
@@ -554,6 +562,11 @@ interface Store {
|
|
|
554
562
|
readonly queue: Queue;
|
|
555
563
|
readonly limit?: number;
|
|
556
564
|
}): Promise<readonly ReapedLease[]>;
|
|
565
|
+
upsertTimer(runId: RunId$1, stepId: StepId, fireAt: Date): Promise<void>;
|
|
566
|
+
sweepSignalTimeouts(args: {
|
|
567
|
+
readonly now: Date;
|
|
568
|
+
readonly limit?: number;
|
|
569
|
+
}): Promise<readonly TimedOutSignal[]>;
|
|
557
570
|
settleStep(runId: RunId$1, stepId: StepId, fact: StepCompletedFact | StepFailedFact): Promise<void>;
|
|
558
571
|
recordOnce(runId: RunId$1, stepId: StepId, scope: string, value: Json): Promise<void>;
|
|
559
572
|
getOnce(runId: RunId$1, stepId: StepId, scope: string): Promise<Json | null>;
|
|
@@ -893,6 +906,16 @@ declare class NagiCanceledError extends Error {
|
|
|
893
906
|
readonly concurrencyKey: string;
|
|
894
907
|
});
|
|
895
908
|
}
|
|
909
|
+
declare class NagiSignalTimeoutError extends Error {
|
|
910
|
+
readonly runId: RunId$1;
|
|
911
|
+
readonly stepId: string;
|
|
912
|
+
readonly fireAt: Date;
|
|
913
|
+
constructor({ runId, stepId, fireAt, }: {
|
|
914
|
+
readonly runId: RunId$1;
|
|
915
|
+
readonly stepId: string;
|
|
916
|
+
readonly fireAt: Date;
|
|
917
|
+
});
|
|
918
|
+
}
|
|
896
919
|
declare class NagiFlowSnapshotGoneError extends Error {
|
|
897
920
|
readonly runId: RunId$1;
|
|
898
921
|
readonly flowId: string;
|
|
@@ -941,6 +964,7 @@ declare class InMemoryStore implements Store, StreamTransport {
|
|
|
941
964
|
private readonly childrenByParent;
|
|
942
965
|
private readonly summaries;
|
|
943
966
|
private readonly streamHub;
|
|
967
|
+
private readonly signalTimers;
|
|
944
968
|
private readonly leaseMs;
|
|
945
969
|
constructor(opts?: InMemoryStoreOpts);
|
|
946
970
|
appendFact(runId: RunId$1, fact: Fact): Promise<void>;
|
|
@@ -965,6 +989,7 @@ declare class InMemoryStore implements Store, StreamTransport {
|
|
|
965
989
|
}>;
|
|
966
990
|
}>;
|
|
967
991
|
listChildren(parentRunId: RunId$1): Promise<ReadonlyArray<RunId$1>>;
|
|
992
|
+
private hasActiveChild;
|
|
968
993
|
loadRunState(runId: RunId$1): Promise<RunState>;
|
|
969
994
|
claimStep(runId: RunId$1, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
|
|
970
995
|
extendLease(runId: RunId$1, stepId: StepId, attempt: AttemptNumber, leaseMs: Millis): Promise<void>;
|
|
@@ -983,6 +1008,11 @@ declare class InMemoryStore implements Store, StreamTransport {
|
|
|
983
1008
|
readonly signalName?: string;
|
|
984
1009
|
};
|
|
985
1010
|
}): Promise<SettleSignalResult>;
|
|
1011
|
+
upsertTimer(runId: RunId$1, stepId: StepId, fireAt: Date): Promise<void>;
|
|
1012
|
+
sweepSignalTimeouts(args: {
|
|
1013
|
+
readonly now: Date;
|
|
1014
|
+
readonly limit?: number;
|
|
1015
|
+
}): Promise<readonly TimedOutSignal[]>;
|
|
986
1016
|
recordOnce(runId: RunId$1, stepId: StepId, scope: string, value: Json): Promise<void>;
|
|
987
1017
|
getOnce(runId: RunId$1, stepId: StepId, scope: string): Promise<Json | null>;
|
|
988
1018
|
runStep<T extends Json>(runId: RunId$1, _stepId: StepId, _attempt: AttemptNumber, body: (tx: Tx) => Promise<{
|
|
@@ -1143,6 +1173,19 @@ declare function decideSignal(args: {
|
|
|
1143
1173
|
readonly signalName?: string;
|
|
1144
1174
|
} | undefined;
|
|
1145
1175
|
}): SignalDecision;
|
|
1176
|
+
type TimeoutDecision = {
|
|
1177
|
+
readonly kind: "noop";
|
|
1178
|
+
} | {
|
|
1179
|
+
readonly kind: "fail";
|
|
1180
|
+
readonly attempt: AttemptNumber;
|
|
1181
|
+
readonly fact: StepFailedFact;
|
|
1182
|
+
};
|
|
1183
|
+
declare function decideTimeout(args: {
|
|
1184
|
+
readonly runState: RunState;
|
|
1185
|
+
readonly stepId: StepId;
|
|
1186
|
+
readonly fireAt: Date;
|
|
1187
|
+
readonly at: Date;
|
|
1188
|
+
}): TimeoutDecision;
|
|
1146
1189
|
|
|
1147
1190
|
declare class NagiAbortError extends Error {
|
|
1148
1191
|
readonly runId: RunId$1;
|
|
@@ -1150,4 +1193,4 @@ declare class NagiAbortError extends Error {
|
|
|
1150
1193
|
constructor(runId: RunId$1, kind: "run" | "step");
|
|
1151
1194
|
}
|
|
1152
1195
|
|
|
1153
|
-
export { type Anomaly, type AttemptNumber, type BackoffStrategy, type Builder, type CancelArgs, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, type ClaimToken, type Clock, type ConcurrencyMode, DEFAULT_REAPER_INTERVAL_MS, type Fact, type FactKind, type Flow, type FlowCanceledByConcurrencyFact, type FlowCanceledByOperatorFact, type FlowCanceledExplicitlyFact, type FlowCanceledFact, type FlowCompleteEvent, type FlowCompletedFact, type FlowConcurrency, type FlowConfig, type FlowErrorEvent, type FlowEvent, type FlowFailedFact, type FlowHooks, type FlowIdOf, type FlowInput, type FlowOutput, type FlowRefUpdatedFact, type FlowStartEvent, type FlowStartedFact, type GlobalFact, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, type InferSchemaInput, type InferSchemaOutput, type Json, type LeaseReapedFact, type LogEntry, type LogLevel, type Logger, type MatchArm, type MatchArmGuard, type MatchArmOtherwise, type MatchArmOutput, type MatchArmSelectedFact, type MatchArmShape, type MatchGuardConfig, type Millis, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, type NagiConfig, NagiFlowSnapshotGoneError, type NagiRunConfig, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, type NeedRef, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type Operator, type OperatorAuditOpts, type Optional, type ParentLink, type ParentRef, type PrunableStatus, type PruneOpts, type PruneResult, type QueryRunsOpts, type QueryRunsResult, type QueryRunsWhere, type Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type ReapedLease, type ReaperDecision, type Register, type ReplayMode, type ReplayOpts, type Resolved, type ResolvedConcurrency, type ResolvedNeeds, type RetryPolicy, type RunCancelCause, type RunDescription, RunId, type RunPhase, type RunState, type RunStatus, type RunSummary, type RunView, type RuntimeHandle, type SerializedError, type SettleSignalResult, type SignalBufferedFact, type SignalConfig, type SignalDecision, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SkipReason, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type StartStagedOpts, type StartStagedResult, type Step, type StepAbortRequestedFact, type StepCancelCause, type StepCanceledFact, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepResetFact, type StepRetriedFact, type StepRetryEvent, type StepRunStatus, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type StepView, type Store, type StreamEvent, type StreamTransport, type StreamingStepCtx, type StreamingTaskConfig, type StringKeyOf, type SubflowConfig, type SubflowStepOutput, type TaskConfig, type Trigger, type Tx, type Wf, type Worker, type WorkerConfig, type WorkerRunOnceOpts, type WorkerRunResult, type WorkerRunUntilEmptyOpts, attemptOf, canonicalize, decideExpiredLeaseAction, decideSignal, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
|
|
1196
|
+
export { type Anomaly, type AttemptNumber, type BackoffStrategy, type Builder, type CancelArgs, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, type ClaimToken, type Clock, type ConcurrencyMode, DEFAULT_REAPER_INTERVAL_MS, type Fact, type FactKind, type Flow, type FlowCanceledByConcurrencyFact, type FlowCanceledByOperatorFact, type FlowCanceledExplicitlyFact, type FlowCanceledFact, type FlowCompleteEvent, type FlowCompletedFact, type FlowConcurrency, type FlowConfig, type FlowErrorEvent, type FlowEvent, type FlowFailedFact, type FlowHooks, type FlowIdOf, type FlowInput, type FlowOutput, type FlowRefUpdatedFact, type FlowStartEvent, type FlowStartedFact, type GlobalFact, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, type InferSchemaInput, type InferSchemaOutput, type Json, type LeaseReapedFact, type LogEntry, type LogLevel, type Logger, type MatchArm, type MatchArmGuard, type MatchArmOtherwise, type MatchArmOutput, type MatchArmSelectedFact, type MatchArmShape, type MatchGuardConfig, type Millis, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, type NagiConfig, NagiFlowSnapshotGoneError, type NagiRunConfig, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiValidationError, type NeedRef, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type Operator, type OperatorAuditOpts, type Optional, type ParentLink, type ParentRef, type PrunableStatus, type PruneOpts, type PruneResult, type QueryRunsOpts, type QueryRunsResult, type QueryRunsWhere, type Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type ReapedLease, type ReaperDecision, type Register, type ReplayMode, type ReplayOpts, type Resolved, type ResolvedConcurrency, type ResolvedNeeds, type RetryPolicy, type RunCancelCause, type RunDescription, RunId, type RunPhase, type RunState, type RunStatus, type RunSummary, type RunView, type RuntimeHandle, type SerializedError, type SettleSignalResult, type SignalBufferedFact, type SignalConfig, type SignalDecision, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SkipReason, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type StartStagedOpts, type StartStagedResult, type Step, type StepAbortRequestedFact, type StepCancelCause, type StepCanceledFact, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepResetFact, type StepRetriedFact, type StepRetryEvent, type StepRunStatus, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type StepView, type Store, type StreamEvent, type StreamTransport, type StreamingStepCtx, type StreamingTaskConfig, type StringKeyOf, type SubflowConfig, type SubflowStepOutput, type TaskConfig, type TimedOutSignal, type TimeoutDecision, type Trigger, type Tx, type Wf, type Worker, type WorkerConfig, type WorkerRunOnceOpts, type WorkerRunResult, type WorkerRunUntilEmptyOpts, attemptOf, canonicalize, decideExpiredLeaseAction, decideSignal, decideTimeout, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
|
package/dist/index.js
CHANGED
|
@@ -856,6 +856,24 @@ var NagiCanceledError = class extends Error {
|
|
|
856
856
|
};
|
|
857
857
|
}
|
|
858
858
|
};
|
|
859
|
+
var NagiSignalTimeoutError = class extends Error {
|
|
860
|
+
runId;
|
|
861
|
+
stepId;
|
|
862
|
+
fireAt;
|
|
863
|
+
constructor({
|
|
864
|
+
runId,
|
|
865
|
+
stepId,
|
|
866
|
+
fireAt
|
|
867
|
+
}) {
|
|
868
|
+
super(
|
|
869
|
+
`Signal step "${stepId}" (run ${runId}) timed out \u2014 no signal arrived before its deadline ${fireAt.toISOString()}.`
|
|
870
|
+
);
|
|
871
|
+
this.name = "NagiSignalTimeoutError";
|
|
872
|
+
this.runId = runId;
|
|
873
|
+
this.stepId = stepId;
|
|
874
|
+
this.fireAt = fireAt;
|
|
875
|
+
}
|
|
876
|
+
};
|
|
859
877
|
var NagiFlowSnapshotGoneError = class extends Error {
|
|
860
878
|
runId;
|
|
861
879
|
flowId;
|
|
@@ -926,10 +944,13 @@ function serializeError(err) {
|
|
|
926
944
|
|
|
927
945
|
// src/lease-reaper.ts
|
|
928
946
|
function decideExpiredLeaseAction(args) {
|
|
929
|
-
const { lease, stepStatus, now } = args;
|
|
947
|
+
const { lease, stepStatus, childActive, now } = args;
|
|
930
948
|
if (stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
|
|
931
949
|
return { tag: "skip", reason: "terminal" };
|
|
932
950
|
}
|
|
951
|
+
if (childActive) {
|
|
952
|
+
return { tag: "skip", reason: "child-active" };
|
|
953
|
+
}
|
|
933
954
|
if (lease.expiresAt > now) {
|
|
934
955
|
return { tag: "skip", reason: "still-live" };
|
|
935
956
|
}
|
|
@@ -1146,6 +1167,19 @@ function decideSignal(args) {
|
|
|
1146
1167
|
result: { tag: "buffered" }
|
|
1147
1168
|
};
|
|
1148
1169
|
}
|
|
1170
|
+
function decideTimeout(args) {
|
|
1171
|
+
const { runState, stepId, fireAt, at } = args;
|
|
1172
|
+
const step = stepStateOf(runState, stepId);
|
|
1173
|
+
if (step.tag !== "awaitingSignal") return { kind: "noop" };
|
|
1174
|
+
const error = serializeError(
|
|
1175
|
+
new NagiSignalTimeoutError({ runId: runState.runId, stepId, fireAt })
|
|
1176
|
+
);
|
|
1177
|
+
return {
|
|
1178
|
+
kind: "fail",
|
|
1179
|
+
attempt: step.attempt,
|
|
1180
|
+
fact: Facts.stepFailed(runState.runId, stepId, step.attempt, error, at)
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1149
1183
|
function makeSignals(deps) {
|
|
1150
1184
|
const { dispatcher, store, clock, registry, hooks, flowHooks, emitLog } = deps;
|
|
1151
1185
|
async function signal(runId, signalName, payload) {
|
|
@@ -1402,6 +1436,10 @@ var InMemoryStore = class {
|
|
|
1402
1436
|
childrenByParent = /* @__PURE__ */ new Map();
|
|
1403
1437
|
summaries = /* @__PURE__ */ new Map();
|
|
1404
1438
|
streamHub = new InMemoryStreamHub();
|
|
1439
|
+
// Durable signal-timeout deadlines, keyed `${runId}::${stepId}` → fire_at.
|
|
1440
|
+
// The Postgres analogue is the nagi.timer table; this is its in-memory twin
|
|
1441
|
+
// (distinct from the InMemoryClock's setTimeout-based scheduler timers).
|
|
1442
|
+
signalTimers = /* @__PURE__ */ new Map();
|
|
1405
1443
|
leaseMs;
|
|
1406
1444
|
constructor(opts = {}) {
|
|
1407
1445
|
this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
|
|
@@ -1444,6 +1482,7 @@ var InMemoryStore = class {
|
|
|
1444
1482
|
for (const key of this.leases.keys()) {
|
|
1445
1483
|
if (key.startsWith(leasePrefix)) this.leases.delete(key);
|
|
1446
1484
|
}
|
|
1485
|
+
this.signalTimers.delete(`${runId}::${fact.stepId}`);
|
|
1447
1486
|
}
|
|
1448
1487
|
}
|
|
1449
1488
|
async tryStartRun(runId, fact, concurrency) {
|
|
@@ -1487,6 +1526,23 @@ var InMemoryStore = class {
|
|
|
1487
1526
|
if (set === void 0) return [];
|
|
1488
1527
|
return Array.from(set);
|
|
1489
1528
|
}
|
|
1529
|
+
// Does a non-terminal child exist for this (parentRunId, stepId)? Used by the
|
|
1530
|
+
// reaper to leave a subflow step parked while its child still runs (instead
|
|
1531
|
+
// of re-dispatching it at attempt+1). childrenByParent is keyed by parent run
|
|
1532
|
+
// only, so filter on the child's parent.stepId.
|
|
1533
|
+
hasActiveChild(parentRunId, parentStepId) {
|
|
1534
|
+
const childIds = this.childrenByParent.get(parentRunId);
|
|
1535
|
+
if (childIds === void 0) return false;
|
|
1536
|
+
for (const childId of childIds) {
|
|
1537
|
+
const factList = this.facts.get(childId);
|
|
1538
|
+
if (factList === void 0) continue;
|
|
1539
|
+
const child = foldRun(childId, factList);
|
|
1540
|
+
if (child.parent?.stepId === parentStepId && !isTerminalRun(child)) {
|
|
1541
|
+
return true;
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
return false;
|
|
1545
|
+
}
|
|
1490
1546
|
async loadRunState(runId) {
|
|
1491
1547
|
return foldRun(runId, this.facts.get(runId) ?? []);
|
|
1492
1548
|
}
|
|
@@ -1540,6 +1596,7 @@ var InMemoryStore = class {
|
|
|
1540
1596
|
expiresAt: c.expiresAt
|
|
1541
1597
|
},
|
|
1542
1598
|
stepStatus,
|
|
1599
|
+
childActive: this.hasActiveChild(c.runId, c.stepId),
|
|
1543
1600
|
now
|
|
1544
1601
|
});
|
|
1545
1602
|
if (decision.tag === "skip") continue;
|
|
@@ -1583,9 +1640,44 @@ var InMemoryStore = class {
|
|
|
1583
1640
|
case "deliver":
|
|
1584
1641
|
await this.appendFact(runId, decision.received);
|
|
1585
1642
|
await this.appendFact(runId, decision.completed);
|
|
1643
|
+
this.signalTimers.delete(`${runId}::${stepId}`);
|
|
1586
1644
|
return decision.result;
|
|
1587
1645
|
}
|
|
1588
1646
|
}
|
|
1647
|
+
async upsertTimer(runId, stepId, fireAt) {
|
|
1648
|
+
const key = `${runId}::${stepId}`;
|
|
1649
|
+
if (!this.signalTimers.has(key)) this.signalTimers.set(key, fireAt);
|
|
1650
|
+
}
|
|
1651
|
+
async sweepSignalTimeouts(args) {
|
|
1652
|
+
const { now, limit = 100 } = args;
|
|
1653
|
+
const timedOut = [];
|
|
1654
|
+
const due = [];
|
|
1655
|
+
for (const [key, fireAt] of this.signalTimers) {
|
|
1656
|
+
if (due.length >= limit) break;
|
|
1657
|
+
if (fireAt > now) continue;
|
|
1658
|
+
const sep = key.indexOf("::");
|
|
1659
|
+
due.push({
|
|
1660
|
+
key,
|
|
1661
|
+
runId: key.slice(0, sep),
|
|
1662
|
+
stepId: key.slice(sep + 2)
|
|
1663
|
+
});
|
|
1664
|
+
}
|
|
1665
|
+
for (const { key, runId, stepId } of due) {
|
|
1666
|
+
const fireAt = this.signalTimers.get(key);
|
|
1667
|
+
if (fireAt === void 0) continue;
|
|
1668
|
+
const runState = foldRun(runId, this.facts.get(runId) ?? []);
|
|
1669
|
+
const decision = decideTimeout({ runState, stepId, fireAt, at: now });
|
|
1670
|
+
this.signalTimers.delete(key);
|
|
1671
|
+
if (decision.kind === "noop") continue;
|
|
1672
|
+
await this.appendFact(runId, decision.fact);
|
|
1673
|
+
const leasePrefix = `${runId}::${stepId}::`;
|
|
1674
|
+
for (const k of this.leases.keys()) {
|
|
1675
|
+
if (k.startsWith(leasePrefix)) this.leases.delete(k);
|
|
1676
|
+
}
|
|
1677
|
+
timedOut.push({ runId, stepId, attempt: decision.attempt, fireAt });
|
|
1678
|
+
}
|
|
1679
|
+
return timedOut;
|
|
1680
|
+
}
|
|
1589
1681
|
async recordOnce(runId, stepId, scope, value) {
|
|
1590
1682
|
this.onces.set(`${runId}::${stepId}::${scope}`, value);
|
|
1591
1683
|
}
|
|
@@ -2026,8 +2118,8 @@ var RunId = {
|
|
|
2026
2118
|
return s;
|
|
2027
2119
|
}
|
|
2028
2120
|
};
|
|
2029
|
-
async function deriveChildRunId(
|
|
2030
|
-
const seed = `nagi:subflow:${
|
|
2121
|
+
async function deriveChildRunId(key) {
|
|
2122
|
+
const seed = `nagi:subflow:${key.runId}:${key.stepId}:gen${key.generation}`;
|
|
2031
2123
|
const digest = await crypto.subtle.digest(
|
|
2032
2124
|
"SHA-256",
|
|
2033
2125
|
new TextEncoder().encode(seed)
|
|
@@ -2473,6 +2565,13 @@ function makeActivityCtx(args) {
|
|
|
2473
2565
|
}
|
|
2474
2566
|
|
|
2475
2567
|
// src/exec/message.ts
|
|
2568
|
+
function subflowGeneration(state, stepId) {
|
|
2569
|
+
let n = 0;
|
|
2570
|
+
for (const f of state.facts) {
|
|
2571
|
+
if (f.kind === "step.reset" && f.stepId === stepId) n++;
|
|
2572
|
+
}
|
|
2573
|
+
return n;
|
|
2574
|
+
}
|
|
2476
2575
|
function makeMessage(deps, hooks, progression) {
|
|
2477
2576
|
const { fireHook, fireStepLifecycle } = hooks;
|
|
2478
2577
|
const { advance } = progression;
|
|
@@ -2536,10 +2635,18 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2536
2635
|
const { store, clock } = deps;
|
|
2537
2636
|
const { runId, stepId, attempt } = message;
|
|
2538
2637
|
const handler = handlerDef(def);
|
|
2638
|
+
const startedAt = clock.now();
|
|
2539
2639
|
await store.appendFact(
|
|
2540
2640
|
runId,
|
|
2541
|
-
Facts.stepStarted(runId, stepId, attempt, def.kind,
|
|
2641
|
+
Facts.stepStarted(runId, stepId, attempt, def.kind, startedAt)
|
|
2542
2642
|
);
|
|
2643
|
+
if (def.kind === "signal" && def.timeoutMs != null) {
|
|
2644
|
+
await store.upsertTimer(
|
|
2645
|
+
runId,
|
|
2646
|
+
stepId,
|
|
2647
|
+
new Date(startedAt.getTime() + def.timeoutMs)
|
|
2648
|
+
);
|
|
2649
|
+
}
|
|
2543
2650
|
const startCarriesInput = def.kind === "task" || def.kind === "activity" || def.kind === "streaming" || def.kind === "subflow";
|
|
2544
2651
|
const input = startCarriesInput ? state.input : null;
|
|
2545
2652
|
await fireStepLifecycle(
|
|
@@ -2610,8 +2717,7 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2610
2717
|
await executeMatch({ def, runId, stepId, state });
|
|
2611
2718
|
return { tag: "advance" };
|
|
2612
2719
|
case "subflow":
|
|
2613
|
-
await executeSubflow({ def, runId, stepId, attempt, state });
|
|
2614
|
-
return { tag: "parked" };
|
|
2720
|
+
return await executeSubflow({ def, runId, stepId, attempt, state });
|
|
2615
2721
|
}
|
|
2616
2722
|
}
|
|
2617
2723
|
async function interpret(args) {
|
|
@@ -2781,14 +2887,23 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2781
2887
|
`Subflow step "${stepId}" references child flow "${def.childFlowId}" which is not registered with nagi(). Pass it to flows[].`
|
|
2782
2888
|
);
|
|
2783
2889
|
}
|
|
2890
|
+
const generation = subflowGeneration(state, stepId);
|
|
2891
|
+
const childRunId = await deriveChildRunId({ runId, stepId, generation });
|
|
2892
|
+
const childState = await deps.store.loadRunState(childRunId);
|
|
2893
|
+
if (isTerminalRun(childState)) {
|
|
2894
|
+
await progression.wakeParentFromChild(childRunId);
|
|
2895
|
+
return { tag: "parked" };
|
|
2896
|
+
}
|
|
2784
2897
|
const parentInput = state.input;
|
|
2785
2898
|
const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
|
|
2786
2899
|
const childInput = def.buildInput({ input: parentInput, needs });
|
|
2787
2900
|
await deps.startChildRun({
|
|
2788
2901
|
child,
|
|
2789
2902
|
childInput,
|
|
2790
|
-
parent: { runId, stepId, attempt }
|
|
2903
|
+
parent: { runId, stepId, attempt },
|
|
2904
|
+
generation
|
|
2791
2905
|
});
|
|
2906
|
+
return { tag: "parked" };
|
|
2792
2907
|
}
|
|
2793
2908
|
async function executeMatch(args) {
|
|
2794
2909
|
const { def, runId, stepId, state } = args;
|
|
@@ -2889,6 +3004,44 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2889
3004
|
|
|
2890
3005
|
// src/exec/progression.ts
|
|
2891
3006
|
var MAX_ADVANCE_ITERS = 1024;
|
|
3007
|
+
function subflowOutcomeOf(childRunId, child) {
|
|
3008
|
+
switch (child.phase.tag) {
|
|
3009
|
+
case "completed":
|
|
3010
|
+
return { kind: "completed", output: child.phase.output };
|
|
3011
|
+
case "failed":
|
|
3012
|
+
return { kind: "failed", error: child.phase.error };
|
|
3013
|
+
case "canceled":
|
|
3014
|
+
return {
|
|
3015
|
+
kind: "canceled",
|
|
3016
|
+
error: cancelCauseToError(childRunId, child.phase.cause)
|
|
3017
|
+
};
|
|
3018
|
+
default:
|
|
3019
|
+
return void 0;
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
function cancelCauseToError(runId, cause) {
|
|
3023
|
+
switch (cause.kind) {
|
|
3024
|
+
case "concurrency":
|
|
3025
|
+
return {
|
|
3026
|
+
name: "NagiCanceledError",
|
|
3027
|
+
message: `Run ${runId} was canceled (superseded by ${cause.canceledByRunId})`,
|
|
3028
|
+
cause: {
|
|
3029
|
+
canceledByRunId: cause.canceledByRunId,
|
|
3030
|
+
concurrencyKey: cause.concurrencyKey
|
|
3031
|
+
}
|
|
3032
|
+
};
|
|
3033
|
+
case "explicit":
|
|
3034
|
+
return {
|
|
3035
|
+
name: "NagiCanceledError",
|
|
3036
|
+
message: `Run ${runId} was canceled: ${cause.reason}`
|
|
3037
|
+
};
|
|
3038
|
+
case "operator":
|
|
3039
|
+
return {
|
|
3040
|
+
name: "NagiCanceledError",
|
|
3041
|
+
message: `Run ${runId} was canceled by ${cause.actor}: ${cause.reason}`
|
|
3042
|
+
};
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
2892
3045
|
function makeProgression(deps, hooks) {
|
|
2893
3046
|
const { fireHook } = hooks;
|
|
2894
3047
|
async function advance(runId) {
|
|
@@ -3052,7 +3205,13 @@ function makeProgression(deps, hooks) {
|
|
|
3052
3205
|
});
|
|
3053
3206
|
await advance(parentRunId);
|
|
3054
3207
|
}
|
|
3055
|
-
|
|
3208
|
+
async function wakeParentFromChild(childRunId) {
|
|
3209
|
+
const child = await deps.store.loadRunState(childRunId);
|
|
3210
|
+
const outcome = subflowOutcomeOf(childRunId, child);
|
|
3211
|
+
if (outcome === void 0) return;
|
|
3212
|
+
await propagateToParent(childRunId, outcome);
|
|
3213
|
+
}
|
|
3214
|
+
return { advance, propagateToParent, wakeParentFromChild };
|
|
3056
3215
|
}
|
|
3057
3216
|
|
|
3058
3217
|
// src/dispatch.ts
|
|
@@ -3060,10 +3219,36 @@ function makeDispatcher(deps) {
|
|
|
3060
3219
|
const hooks = makeHooks(deps);
|
|
3061
3220
|
const progression = makeProgression(deps, hooks);
|
|
3062
3221
|
const message = makeMessage(deps, hooks, progression);
|
|
3222
|
+
async function sweepTimers(now) {
|
|
3223
|
+
const timedOut = await deps.store.sweepSignalTimeouts({ now });
|
|
3224
|
+
for (const { runId, stepId, attempt, fireAt } of timedOut) {
|
|
3225
|
+
if (deps.hooks?.onStepError) {
|
|
3226
|
+
const flow2 = await deps.flowFor(runId);
|
|
3227
|
+
await hooks.fireHook(
|
|
3228
|
+
deps.hooks.onStepError,
|
|
3229
|
+
{
|
|
3230
|
+
runId,
|
|
3231
|
+
flowId: flow2.id,
|
|
3232
|
+
stepId,
|
|
3233
|
+
attempt,
|
|
3234
|
+
kind: "signal",
|
|
3235
|
+
error: serializeError(
|
|
3236
|
+
new NagiSignalTimeoutError({ runId, stepId, fireAt })
|
|
3237
|
+
),
|
|
3238
|
+
at: now
|
|
3239
|
+
},
|
|
3240
|
+
"onStepError"
|
|
3241
|
+
);
|
|
3242
|
+
}
|
|
3243
|
+
await progression.advance(runId);
|
|
3244
|
+
}
|
|
3245
|
+
return timedOut.length;
|
|
3246
|
+
}
|
|
3063
3247
|
return {
|
|
3064
3248
|
dispatchMessage: message.dispatchMessage,
|
|
3065
3249
|
advance: progression.advance,
|
|
3066
|
-
propagateToParent: progression.propagateToParent
|
|
3250
|
+
propagateToParent: progression.propagateToParent,
|
|
3251
|
+
sweepTimers
|
|
3067
3252
|
};
|
|
3068
3253
|
}
|
|
3069
3254
|
|
|
@@ -3364,6 +3549,7 @@ async function drainInline(dispatcher, queue) {
|
|
|
3364
3549
|
// src/worker.ts
|
|
3365
3550
|
var DEFAULT_CONCURRENCY = 4;
|
|
3366
3551
|
var DEFAULT_POLL_INTERVAL_MS = 1e3;
|
|
3552
|
+
var DEFAULT_TIMER_SWEEP_INTERVAL_MS = 3e4;
|
|
3367
3553
|
function makeWorker(deps, config) {
|
|
3368
3554
|
return new WorkerImpl(deps, config);
|
|
3369
3555
|
}
|
|
@@ -3374,6 +3560,8 @@ var WorkerImpl = class {
|
|
|
3374
3560
|
this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
3375
3561
|
this.signal = config?.signal;
|
|
3376
3562
|
this.dispatcher = makeDispatcher(deps);
|
|
3563
|
+
this.timerSweepIntervalMs = config?.timerSweepIntervalMs ?? DEFAULT_TIMER_SWEEP_INTERVAL_MS;
|
|
3564
|
+
this.lastTimerSweepAt = this.deps.clock.now().getTime();
|
|
3377
3565
|
}
|
|
3378
3566
|
deps;
|
|
3379
3567
|
inFlight = 0;
|
|
@@ -3381,8 +3569,11 @@ var WorkerImpl = class {
|
|
|
3381
3569
|
pollIntervalMs;
|
|
3382
3570
|
signal;
|
|
3383
3571
|
dispatcher;
|
|
3572
|
+
timerSweepIntervalMs;
|
|
3573
|
+
lastTimerSweepAt;
|
|
3384
3574
|
async run() {
|
|
3385
3575
|
while (!this.aborted()) {
|
|
3576
|
+
await this.maybeSweepTimers();
|
|
3386
3577
|
const slots = this.concurrency - this.inFlight;
|
|
3387
3578
|
if (slots <= 0) {
|
|
3388
3579
|
await this.sleep(50);
|
|
@@ -3467,6 +3658,26 @@ var WorkerImpl = class {
|
|
|
3467
3658
|
await this.deps.clock.sleep(50);
|
|
3468
3659
|
}
|
|
3469
3660
|
}
|
|
3661
|
+
// Sweep elapsed signal timeouts on cadence. Runs inline in the dispatch loop
|
|
3662
|
+
// (not fired concurrently) so two sweeps never overlap; at 30s with a handful
|
|
3663
|
+
// of timers the cost is negligible. Errors are logged, never thrown — a failed
|
|
3664
|
+
// sweep must not kill the worker; the next tick retries.
|
|
3665
|
+
async maybeSweepTimers() {
|
|
3666
|
+
if (this.timerSweepIntervalMs <= 0) return;
|
|
3667
|
+
const now = this.deps.clock.now();
|
|
3668
|
+
if (now.getTime() - this.lastTimerSweepAt < this.timerSweepIntervalMs)
|
|
3669
|
+
return;
|
|
3670
|
+
this.lastTimerSweepAt = now.getTime();
|
|
3671
|
+
try {
|
|
3672
|
+
await this.dispatcher.sweepTimers(now);
|
|
3673
|
+
} catch (err) {
|
|
3674
|
+
this.deps.emitLog({
|
|
3675
|
+
level: "warn",
|
|
3676
|
+
msg: "worker: signal-timeout sweep failed",
|
|
3677
|
+
attrs: { error: String(err) }
|
|
3678
|
+
});
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3470
3681
|
aborted() {
|
|
3471
3682
|
return this.signal?.aborted === true;
|
|
3472
3683
|
}
|
|
@@ -3615,14 +3826,18 @@ async function nagiImpl(config) {
|
|
|
3615
3826
|
return { started: true };
|
|
3616
3827
|
}
|
|
3617
3828
|
async function startChildRun(args) {
|
|
3618
|
-
const { child, childInput, parent } = args;
|
|
3829
|
+
const { child, childInput, parent, generation } = args;
|
|
3619
3830
|
if (!registry.has(child.id)) {
|
|
3620
3831
|
throw new NagiRuntimeError(
|
|
3621
3832
|
`Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
|
|
3622
3833
|
);
|
|
3623
3834
|
}
|
|
3624
3835
|
const validated = await validate(child.input, childInput);
|
|
3625
|
-
const childRunId = await deriveChildRunId(
|
|
3836
|
+
const childRunId = await deriveChildRunId({
|
|
3837
|
+
runId: parent.runId,
|
|
3838
|
+
stepId: parent.stepId,
|
|
3839
|
+
generation
|
|
3840
|
+
});
|
|
3626
3841
|
await startRunInternal({
|
|
3627
3842
|
flow: child,
|
|
3628
3843
|
validatedInput: validated,
|
|
@@ -4011,6 +4226,6 @@ function bindQueueToTx(queue, tx) {
|
|
|
4011
4226
|
return queue;
|
|
4012
4227
|
}
|
|
4013
4228
|
|
|
4014
|
-
export { DEFAULT_REAPER_INTERVAL_MS, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, RunId, attemptOf, canonicalize, decideExpiredLeaseAction, decideSignal, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
|
|
4229
|
+
export { DEFAULT_REAPER_INTERVAL_MS, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiValidationError, RunId, attemptOf, canonicalize, decideExpiredLeaseAction, decideSignal, decideTimeout, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
|
|
4015
4230
|
//# sourceMappingURL=index.js.map
|
|
4016
4231
|
//# sourceMappingURL=index.js.map
|