Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/worker-communication.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const runtime = createDitto({
- **Commit and persistence.** `operation.committed` names the accepted attempt. In a Graph it follows output validation. `checkpoint.saved` follows the host’s successful save and includes the checkpoint digest. Graph events identify the run and leaf; Graph checkpoint events list confirmed and uncertain leaf IDs. A checkpointed Graph keeps its run identity on resume; each configured Loop iteration has a distinct Graph run. Restoring confirmed outputs emits no new attempt. `checkpoint.restored` reports the loaded snapshot. To observe offline reconciliation, pass the same observer as the third argument to `reconcileGraphCheckpoint`. Its `checkpoint.reconciled` event reports the decision; the host still owns the save.
- **Worker state.** `worker.unavailable` reports an observed IPC disconnect or a registration marked unavailable. HTTP timeouts describe an attempt and do not establish that the whole Worker is down. Observers run at the dispatcher, without waiting for async exporters. An observer failure does not affect execution.
- **Failover.** The budget includes the initial dispatch. An unpinned call can move to another registered compatible Worker with capacity; each Worker ID is tried once. The default policy permits only `not_sent` channel, worker-exit, communication and timeout failures. Invalid requests, protocol errors, remote application errors and pinned calls propagate. Cancellation stops further attempts. `recovery.decided` records the choice and, on retry, the next Worker.
- **Unknown outcomes.** Supply `shouldRetry({ operationId, node, input, error, signal })` for application decisions. It may await a receipt and must return true only when replay is safe. Side-effecting operations need a shared idempotency key or equivalent coordination across replicas. The budget applies to this live invocation. Pending checkpoint intents still require explicit reconciliation after a restart.
- **Unknown outcomes.** Supply `shouldRetry({ operationId, node, input, error, signal })` for application decisions. It may await a receipt and must return true only when replay is safe. If it throws or rejects, the call stops: `recovery.decided` records `stop` and the original transport failure propagates. Side-effecting operations need a shared idempotency key or equivalent coordination across replicas. The budget applies to this live invocation. Pending checkpoint intents still require explicit reconciliation after a restart.

During shutdown, first stop accepting new HTTP requests and await application-level work, then close the Runtime and Server. Owners close external MCP and Provider connections. `registerRemote` only adds a local directory entry; it does not start a server or copy Worker code to another machine.

Expand Down
2 changes: 1 addition & 1 deletion docs/worker-communication.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const runtime = createDitto({
- **区分采纳和持久化。** `operation.committed` 指明采纳的尝试,在 Graph 中发生于节点输出校验之后。宿主成功保存后才产生 `checkpoint.saved`,其中带检查点摘要。Graph 调用带运行和叶子节点标识,Graph 检查点事件列出已确认和待核对的叶子 ID。Graph 检查点恢复时沿用运行标识,配置化 Loop 的每轮 Graph 则有独立标识。恢复已确认输出时直接复用结果。`checkpoint.restored` 标明读到的快照。离线核对时可将同一观察函数作为第三个参数传给 `reconcileGraphCheckpoint`,通过 `checkpoint.reconciled` 记录核对决定,再由宿主持久保存。
- **观察 Worker 状态。** IPC 断线或宿主将注册实例标为不可用时产生 `worker.unavailable`。HTTP 超时仅反映本次尝试的情况。事件由派发方记录,调度器不等待异步导出,观察函数异常也不会改变执行结果。
- **跨实例重试。** 次数上限包含首次尝试。未固定绑定的调用可以转到另一个已注册、能力匹配且有空闲容量的实例,每个 Worker ID 最多尝试一次。默认策略只重试状态为 `not_sent` 的通道关闭、Worker 退出、通信错误和超时。参数错误、协议错误、远端业务异常和固定绑定直接返回错误。取消后停止派发。`recovery.decided` 记录决定,重试时也记录目标 Worker。
- **核对未知结果。** 可提供 `shouldRetry({ operationId, node, input, error, signal })`,异步查询回执,确认可安全重放时返回 true。涉及外部写入时,各副本需要共享幂等键或等效协调机制。尝试预算作用于本次在线调用;进程重启后,检查点中的未确认意图仍需显式核对。
- **核对未知结果。** 可提供 `shouldRetry({ operationId, node, input, error, signal })`,异步查询回执,确认可安全重放时返回 true。回调抛出异常或返回被拒绝的 Promise 时停止重试:`recovery.decided` 记录 `stop`,调用方收到原来的传输错误。涉及外部写入时,各副本需要共享幂等键或等效协调机制。尝试预算作用于本次在线调用;进程重启后,检查点中的未确认意图仍需显式核对。

服务停止时先停止接收新 HTTP 请求,等待应用顶层任务,再关闭 Runtime 和 Server;MCP、Provider 外部连接由拥有者关闭。`registerRemote` 只是本地目录登记,不会启动服务器或把 Worker 代码复制到另一台机器。

Expand Down
3 changes: 2 additions & 1 deletion src/runtime/execution-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ export interface ExecutionAttempt extends ExecutionOperation {
export interface RecoveryPolicy {
/** Total physical attempts, including the first. Each Worker ID is tried at most once. */
readonly maxAttempts: number;
/** Return true only if replay is safe. Without a callback only unsent transport failures qualify. */
/** Return true only if replay is safe. Without a callback only unsent transport failures qualify.
* If the callback throws or rejects, the call stops and the original TransportError propagates. */
readonly shouldRetry?: (failure: ExecutionAttempt & {
readonly error: TransportError; readonly input: unknown; readonly signal?: AbortSignal;
}) => boolean | Promise<boolean>;
Expand Down
9 changes: 6 additions & 3 deletions src/runtime/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,9 +310,12 @@ export class DittoRuntime implements RuntimeClient {
if (!policy || !transportFailure) throw error;
let next: WorkerEntry | undefined;
if (!options.workerId && number < policy.maxAttempts && recoverableCodes.has(error.code)) {
const retry = policy.shouldRetry
? await policy.shouldRetry({ ...attempt, error, input, ...(options.signal && { signal: options.signal }) })
: error.status === "not_sent";
let retry = false;
try {
retry = policy.shouldRetry
? await policy.shouldRetry({ ...attempt, error, input, ...(options.signal && { signal: options.signal }) })
: error.status === "not_sent";
} catch { /* A failed safety check is not consent to replay; the transport failure stays authoritative. */ }
options.signal?.throwIfAborted();
if (retry) {
(tried ??= new Set()).add(entry.address.workerId);
Expand Down
16 changes: 16 additions & 0 deletions test/runtime-failover.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,22 @@ test("cancellation during an asynchronous recovery decision prevents redispatch"
await runtime.close();
});

test("a failing recovery decision stops and keeps the original transport failure", async () => {
const fail = new Error("receipt store unavailable");
for (const shouldRetry of [() => { throw fail; }, async () => { throw fail; }]) {
const { runtime, calls, events } = fixture({ maxAttempts: 2, shouldRetry }, async envelope => {
throw new TransportError("TIMEOUT", "outcome_unknown", envelope, "timeout");
});
await assert.rejects(runtime.invoke("MEMORY.GET", {}), (e: unknown) =>
e instanceof TransportError && e.code === "TIMEOUT" && e.status === "outcome_unknown" && e.invocationId === calls[0]?.id);
assert.equal(calls.length, 1);
assert.deepEqual(events.map(e => e.type), ["operation.dispatched", "attempt.started", "attempt.failed", "recovery.decided"]);
const decision = events.at(-1);
assert.ok(decision?.type === "recovery.decided" && decision.decision === "stop" && decision.nextWorkerId === undefined);
await runtime.close();
}
});

test("after a real IPC worker exits, an approved read continues on a second replica", async () => {
const child = fork(new URL("./fixtures/runtime-worker.js", import.meta.url), [], {
env: { ...process.env, TEST_WORKER_TOKEN: "local-test" }, stdio: ["ignore", "ignore", "inherit", "ipc"],
Expand Down